javascript - 旋转 Canvas 内容

标签 javascript html canvas

我制作了一个图像编辑器,我可以在其中上传图像进行裁剪。

现在我应该旋转该图像,但我无法做到这一点。

我找到了一些旋转 Canvas 的代码片段,但我看不到结果, Canvas 不旋转。

ctx.translate(50,50);
ctx.rotate(angle / 180 / Math.PI);
ctx.drawImage(orig_src, -16, -16);
ctx.restore();

我是 HTML/JavaScript 新手,所以代码中可能有问题。

代码如下: https://jsfiddle.net/marcom89/awb7320h/1/

最佳答案

使用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/

相关文章:

javascript - React Router 渲染空 div

javascript - 在 react 组件中动画淡出元素

php - 如何在php网页中获取iframe的颜色?

javascript - document.getElementById 返回 [object HTMLDivElement]

javascript - Javascript 中的命令 fillRect() 不起作用

javascript - Angular 5 : ERROR Error: Uncaught (in promise): Error: Cannot assign to a reference or variable

javascript - 像在 twitter 上一样用 svelte 打字时给 #hashtags 上色

javascript - 如何使用键旋转和平移 html 文档中的图像? (javascript)

javascript - 无法在javascript中正确加载图像

html - 用于文本旋转的 CSS3 与 Canvas