我正在尝试让画布工作,我正在尝试做的是制作图像(从现有图像中)并在其上放置文本。我希望文本在图像的左侧旋转。我尝试旋转文本的那一刻,在画布上再也看不到它了。我正在使用以下解决方案:
var ctx = canvas.getContext("2d");
ctx.drawImage(img,0,0);
ctx.save();
ctx.rotate(-0.5*Math.PI);
ctx.font = "12px Arial";
ctx.fillStyle = 'white';
ctx.textBaseline = 'top';
ctx.fillText("copyright", 0, 0);
ctx.restore();
var image = canvas.toDataURL("image/jpeg");
使用此解决方案,我再也看不到文字了。当我删除旋转并在下面添加代码时,一切工作正常,图像被渲染,文本在图像上被渲染。
var ctx = canvas.getContext("2d");
ctx.drawImage(img,0,0);
ctx.rotate(-0.5*Math.PI);
ctx.font = "12px Arial";
ctx.fillStyle = 'white';
ctx.textBaseline = 'top';
ctx.fillText("copyright", 0, 0);
var image = canvas.toDataURL("image/jpeg");
谁能看到我犯的错误,还是有人可以解决我的问题?
我编辑了一个显示问题的jsfiddle http://jsfiddle.net/7kzuN/4/
旋转之前,应始终设置旋转点。
可以将旋转点想像成是用笔尖压在一张纸上。
旋转时,纸张将绕笔尖旋转。
您可以使用context.translate(x,y)设置旋转点。
要在图片的左侧旋转,您可以翻译如下内容:
// set the rotation point
ctx.translate(6,img.height/2);
这会将旋转点设置为离开图像左侧和垂直中心6个像素。
这是示例代码和演示:http : //jsfiddle.net/m1erickson/ANpPm/
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var img=new Image();
img.crossOrigin="anonymous";
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/houseIcon.png";
function start(){
canvas.width=img.width;
canvas.height=img.height;
// draw the image
ctx.drawImage(img,0,0);
// save the unrotated context
ctx.save();
// set the rotation point with translate
ctx.translate(6,img.height/2);
// rotate by -90 degrees
ctx.rotate(-0.5*Math.PI);
// draw the copyright bar
ctx.fillStyle="black";
ctx.fillRect(-img.height/2,-6,img.height,14);
ctx.font = "12px Arial";
ctx.fillStyle = 'white';
ctx.textBaseline = 'top';
ctx.fillText("copyright", -img.height/2+5,-6);
// restore the context to its unrotated state
ctx.restore();
// save the image+text to a dataURL
var image = canvas.toDataURL("image/jpeg");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句