canvas 使用细节

来源:互联网 发布:淘宝欠下贷款怎么协商 编辑:程序博客网 时间:2024/06/07 15:20

最近在使用html5做项目界面,需要使用到canvas元素。

canvas元素一般很难用到。特定项目中,也需要使用到canvas元素。

<!DOCTYPE HTML><html><body><canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">Your browser does not support the canvas element.</canvas><script type="text/javascript">var c=document.getElementById("myCanvas");var cxt=c.getContext("2d");cxt.fillStyle="#FF0000";cxt.beginPath();cxt.arc(70,18,15,0,Math.PI*2,true);cxt.closePath();cxt.fill();</script></body></html>


这个是w3school中的例子。在画布中画一个红色的圆。

我的项目中是需要画一个 x 。

<!DOCTYPE HTML><html><body><div><canvas id="myCanvas" width="250" height="100" style="border:1px solid #c3c3c3;">Your browser does not support the canvas element.</canvas></div><script type="text/javascript">var c = document.getElementById("myCanvas");var cxt = c.getContext("2d");cxt.moveTo(0,0);cxt.lineTo(250,100);cxt.moveTo(250,0);cxt.lineTo(0,100);cxt.lineWidth = 1; cxt.strokeStyle = '#c3c3c3'; cxt.stroke();cxt.fillText("Hello WORLD!", 95, 30);</script></body></html>

的确是画了个x。但是问题来了,这个canvas的宽和高是固定死的。

但是我要画的canvas的宽度,是改变的。

我先使用jQuery动态给canvas添加style。

$("#myCanvas").css("width",400);

但是画出来的并不是我想要的x。

$(function(){function drawImage(){var canvas_width = $(window).width();//获得浏览器窗口的高度。$("#myCanvas").css("width",canvas_width).css("height",180);var c = document.getElementById("job_item_canvas");var cxt = c.getContext("2d");cxt.moveTo(0,0);cxt.lineTo(canvas_width,180);cxt.moveTo(0,180);cxt.lineTo(canvas_width,0);cxt.lineWidth = 1; cxt.strokeStyle = '#9A9A9A'; cxt.stroke();cxt.fillText("helloWord!", canvas_width/2 , 30);}window.onload = drawImage;});


出现了这种状况。

最后找到了结果。

$("#myCanvas").attr("width",canvas_width).attr("height",180);

而不能使用,$("#myCanvas").css("width",canvas_width).css("height",180);

因为canvas 里面有自带的width 和 height 元素。而上面的只是添加了canvas style里面的width 和 height。这两者是有区别的。



0 0
原创粉丝点击