我制作了一个图像编辑器,我可以在其中上传图像进行裁剪。
现在我应该旋转该图像,但我无法做到这一点。
我找到了一些旋转 Canvas 的代码片段,但我看不到结果, Canvas 不旋转。
ctx.translate(50,50);
ctx.rotate(angle / 180 / Math.PI);
ctx.drawImage(orig_src, -16, -16);
ctx.restore();
我是 HTML/JavaScript 新手,所以代码中可能有问题。
最佳答案
使用setTransform
绘制通过中心旋转、缩放和定位的图像
// ctx is the 2D context
// image is the image to render
// x,y position on the canvas to put the image center
// scale the scale of the image 1 = no scale, < 1 smaller, > 1 bigger
// angle the rotation of the image in radians with positive going clockwise
// returns undefined
function drawImage(ctx, image, x, y, scale, angle){
ctx.setTransform(scale, 0, 0, scale, x, y); // set the scale and position
ctx.rotate(angle); // set the rotation
ctx.drawImage(image, -image.width / 2, -image.height / 2); // draw the image offset half its width and height
ctx.setTransform(1, 0, 0, 1, 0, 0); // restore the transform to default
}
关于javascript - 旋转 Canvas 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44107241/