canvas-基本应用-例子2

来源:互联网 发布:java 调用ireport 编辑:程序博客网 时间:2024/06/03 14:30

学习来源于 https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_usage


<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>simple</title>    <style type="text/css">        canvas{            border:1px dashed black;        }    </style></head><body onload="draw()"><h1>A simple example</h1><canvas id="canvas" width="400px" height="400px"></canvas><script type="text/javascript">    function draw() {        var canvas = document.getElementById("canvas");        var ctx = canvas.getContext('2d');        ctx.fillStyle='rgb(200,0,0)';        ctx.fillRect(20,20,100,100);        ctx.fillStyle='rgba(0,0,200,0.5)';        ctx.fillRect(50,50,100,100);    }</script></body></html>
效果:

学习过程碰到的问题:

1.fillStyle是一个属性不是一个函数

2.rgb和rbga的区别

rgb(200,0,0)rgba(0,0,200,0.5)
最后一个参数为透明度

3.宽度和高度应该在canvas标签中指定,若在css中指定,可能图像会发生扭曲

比如如下代码:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>simple</title>    <style type="text/css">        canvas {            border: 1px dashed black;            width: 400px;            height: 400px;        }    </style></head><body onload="draw()"><h1>A simple example</h1><!--<canvas id="canvas" width="400px" height="400px"></canvas>--><canvas id="canvas"></canvas><script type="text/javascript">    function draw() {        var canvas = document.getElementById("canvas");        var ctx = canvas.getContext('2d');        ctx.fillStyle = 'rgb(200,0,0)';        ctx.fillRect(20, 20, 100, 100);        ctx.fillStyle = 'rgba(0,0,200,0.5)';        ctx.fillRect(50, 50, 100, 100);    }</script></body></html>
得到的效果却是这样的:


At first sight a <canvas> looks like the <img> element, with the only clear difference being that it doesn't have the src and alt attributes. Indeed, the <canvas> element has only two attributes, width and height. These are both optional and can also be set using DOM properties. When no width and height attributes are specified, the canvas will initially be 300 pixels wide and 150 pixels high. The element can be sized arbitrarily by CSS, but during rendering the image is scaled to fit its layout size: if the CSS sizing doesn't respect the ratio of the initial canvas, it will appear distorted.


所以,如果需要指定canvas的宽度和高度,最好还是在canvas标签中进行吧。


原创粉丝点击