簡體   English   中英

旋轉畫布內容

[英]Rotate Canvas content

我已經制作了圖像編輯器,可以在其中上傳圖像以進行裁剪。.現在我應該旋轉該圖像,但是我無法執行此操作...我發現了一些片段可以旋轉畫布,但是我可以看不到結果,畫布不會旋轉。

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

我是HTML / JS的新手,所以代碼中可能有問題。這是代碼: https : //jsfiddle.net/marcom89/awb7320h/1/

感謝您的幫助Marco

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

它幾乎不需要修復保存/恢復和清除畫布(clearRect),也可以直接在方法內部調用“ drawImage”。

小提琴: 這里

    ctx.clearRect(0, 0, resize_canvas.width, resize_canvas.height);
    ctx.save();
    ctx.translate(resize_canvas.width/2,resize_canvas.height/2);
    ctx.rotate(angle / 180 / Math.PI);
    ctx.drawImage(orig_src, -resize_canvas.width/2, -resize_canvas.height/2);
    ctx.restore();

這可能不正確,可能是因為您在翻譯畫布時沒有保存/恢復。 諸如平移和旋轉之類的操作可能會使以后的每個操作弄亂,因此在大多數情況下請記住保存/還原。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM