zoukankan      html  css  js  c++  java
  • canvas需要在标签的属性里定义宽高

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>canvas</title>
    <meta name="Keywords" content="">
    <meta name="author" content="@my_programmer">
    <style type="text/css">
    body{margin:0;}
    canvas{margin:20px; 
    /* 400px;
    height: 300px;*/

    </style>
    </head>
    <body onload="draw()">
    <canvas id="canvas" width=400 height=300 style="border:1px solid #f00;"></canvas>
    <script>
    function draw() {
    var canvas=document.getElementById('canvas');
    var context=canvas.getContext('2d');
    context.beginPath();
    context.moveTo(20,20);
    context.lineTo(200,100);
    context.lineWidth=5;
    context.stroke();
    }
    </script>
    </body>
    </html>

    1.宽:400;高:300;直接写在<canvas>里的效果:

    2、删除<canvas>里的宽高,宽:400;高:300;写在<style>里的效果:

      为什么两者的效果会不一样呢?

      canvas跟其他标签一样,也可以通过css来定义样式。但这里需要注意的是:canvas的默认宽高为300px * 150px,在css中为canvas定义宽高,实际上把宽高为300px * 150px的画布进行了拉伸,如果在这样的情况下进行canvas绘图,你得到的图形可能就是变形的效果。所以,在canvas绘图时,应该在canvas标签里直接定义宽高。

    另外就算写在内联样式里也是会有拉伸bug的:<canvas id="canvas" style=" 400px;height: 300px;"></canvas>

    只能直接作为标签的属性写<canvas id="canvas" width="400px" height="300px"></canvas>,或者在js中动态更改

  • 相关阅读:
    bzoj 3238
    bzoj 3473 后缀自动机多字符串的子串处理方法
    bzoj 2998 第k小字串
    bzoj 3672 利用点分治将CDQ分治推广到树型结构上
    bzoj 3671 贪心
    NOIP模拟题——nan
    NOIP模拟题——kun(栈)
    hduP2586——How far away ?
    DP习题
    NOIP模拟题——来自风平浪静的明天
  • 原文地址:https://www.cnblogs.com/qdog/p/7002770.html
Copyright © 2011-2022 走看看