canvas-基本应用-例子2

学习来源于 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 οnlοad="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 οnlοad="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标签中进行吧。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值