以下是我当前正在使用的代码。通过0
旋转,可以正确缩放图像以填充画布。(类似于background-size: cover
,除了在Canvas上使用JavaScript之外)
我正在尝试添加具有以下功能的旋转功能。
旋转时保持图像居中。我尝试width / 2
在中使用translate
,然后在中使用相反的符号drawImage
,但是如您所见,图像并未居中。我不知道这是否是冲突与我前面x
和y
中心的代码,或者如果这里需要三角?
自动缩放图像以进一步覆盖画布。这些是任意旋转,不是90度增量。我不想裁剪多余的图像以填充画布的各个角落。这比我过去处理的三角函数要复杂得多。
我认为可以使用Math.sin
和来完成此操作Math.cos
,但是自从我使用它们已经很长时间了。我对于如何实现#2尤其不确定。任何帮助,将不胜感激。
var canvas = document.querySelector('canvas')
var context = canvas.getContext('2d')
var image = new Image()
image.src = 'http://i.stack.imgur.com/7FsbT.jpg'
image.onload = function () {
var maxScaleX = canvas.width / image.width
var maxScaleY = canvas.height / image.height
scale = maxScaleX > maxScaleY ? maxScaleX : maxScaleY
var width = image.width * scale
var height = image.height * scale
var x = (width - canvas.width) / -2
var y = (height - canvas.height) / -2
var degrees = 30
context.setTransform(1, 0, 0, 1, 0, 0) // reset previous translate and/or rotate
context.translate(width / 2, height / 2)
context.rotate(degrees * Math.PI / 180)
context.drawImage(image, x - width / 2, y - height / 2, width, height)
}
<canvas width="350" height="150" style="border: solid 1px black"></canvas>
我缩短了代码并简化了用例。您应该能够仅将其包含function drawBestFit()
在您的应用程序中,并使用它来将任何加载的图像填充到任何画布中。
为了更好地了解其工作原理,请查看Blindman67的原始答案-尤其是底部的演示代码段。
var canvas = document.querySelector('canvas')
var context = canvas.getContext('2d')
var image = new Image()
image.src = 'http://i.stack.imgur.com/7FsbT.jpg'
image.onload = function() {
var degrees = 0
loop()
function loop() {
degrees += .5
drawBestFit(context, degrees * Math.PI / 180, image)
requestAnimationFrame(loop)
}
function drawBestFit(ctx, angle, image) {
var dist = Math.sqrt(Math.pow(canvas.width, 2) + Math.pow(canvas.height, 2))
var diagAngle = Math.asin(canvas.height / dist)
var a1 = ((angle % (Math.PI * 2)) + Math.PI * 4) % (Math.PI * 2)
if (a1 > Math.PI)
a1 -= Math.PI
if (a1 > Math.PI / 2 && a1 <= Math.PI)
a1 = (Math.PI / 2) - (a1 - (Math.PI / 2))
var ang1 = Math.PI / 2 - diagAngle - Math.abs(a1)
var ang2 = Math.abs(diagAngle - Math.abs(a1))
var scale1 = Math.cos(ang1) * dist / image.height
var scale2 = Math.cos(ang2) * dist / image.width
var scale = Math.max(scale1, scale2)
var dx = Math.cos(angle) * scale
var dy = Math.sin(angle) * scale
ctx.setTransform(dx, dy, -dy, dx, canvas.width / 2, canvas.height / 2)
ctx.drawImage(image, -image.width / 2, -image.height / 2, image.width, image.height)
ctx.setTransform(1, 0, 0, 1, 0, 0) // reset transformations when done
}
}
<canvas width="350" height="200" style="border: solid 1px black"></canvas>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句