我有一条路径,我想在画布中完全渲染。我知道路径上的初始宽度和高度,但我想旋转并缩放它。
所以我想出了如何确定新的画布大小但是这段代码没有按照我的意愿行事:
let [w, h] = json.imgSize;
ctx.translate(-w / 2, -h / 2);
ctx.scale(json.scale, json.scale);
ctx.rotate(json.rotation);
[w, h] = [canvas.width, canvas.height];
ctx.translate(w / 2, h / 2);
我希望结果是缩放和旋转的路径,但仍然在画布的中心。相反,它围绕路径的左上角旋转。
我的理由是:
以下是我计算画布大小的方法:
// rotate a rectangle and get the resulting extent
let [x, y] = json.imgSize;
let coords = [[-x, -y], [-x, y], [x, y], [x, -y]];
let rect = new ol.geom.MultiPoint(coords);
rect.rotate(json.rotation, [0, 0]);
let extent = rect.getExtent();
[canvas.width, canvas.height] = [ol.extent.getWidth(extent), ol.extent.getHeight(extent)].map(v => v * 0.5);
答案 0 :(得分:2)
如何在中心画布上旋转和缩放绘图:
示例代码和演示:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
// create a rect to rotate
var c=document.createElement('canvas');
var cctx=c.getContext('2d');
c.width=100;
c.height=75;
cctx.fillStyle='skyblue';
cctx.lineWidth=8;
cctx.fillRect(0,0,c.width,c.height);
cctx.strokeRect(0,0,c.width,c.height);
var scale=1;
var direction=1;
var angle=0;
requestAnimationFrame(animate);
function animate(time){
// draw
ctx.clearRect(0,0,cw,ch);
rotateScaleImgAtCenterCanvas(c,scale,angle);
// update
scale+=0.02*direction;
if(scale<0){scale=0;direction=1;}
if(scale>3){scale=3;direction=-1;}
angle+=Math.PI/120;
// request another animation loop
requestAnimationFrame(animate);
}
function rotateScaleImgAtCenterCanvas(img,scale,rotation){
// set the canvas [0,0] origin to center canvas
ctx.translate(canvas.width/2,canvas.height/2);
// scale the canvas
ctx.scale(scale,scale);
// rotate the canvas
ctx.rotate(rotation);
// pull the img leftward & upward so it's center is center-canvas
ctx.translate(-img.width/2,-img.height/2);
// draw the img
ctx.drawImage(img,0,0);
// set transformations back to default
ctx.setTransform(1,0,0,1,0,0);
}
body{ background-color:white; }
#canvas{border:1px solid red; }
<canvas id="canvas" width=378 height=378></canvas>