18-进阶:Canvas 画板

2018-05-14  本文已影响0人  格林姆大师

本节知识点

  1. 获取标签的方法之一(id):document.getElementById(id)
    <div id="canvas"></div>

    <script>
        var div = document.getElementById('canvas')
    </script>
  1. 鼠标按下、移动、松开事件
    <script>
        var div = document.getElementById('canvas')
        //鼠标按下事件
        div.onmousedown = function(downEvent){
            console.log(1)
            var x = downEvent.clientX
            var y = downEvent.clientY
        }
        //鼠标移动事件
        div.onmousemove = function(moveEvent){
            console.log(2)
        }
        //鼠标松开事件
        div.onmouseup = function(upEvent){
            console.log(1)
        }
    </script>

以上事件发生时生成的所有信息都存在 function 的参数里;比如位置信息在 clientX、clientY 里;

  1. 给创建的标签添加样式的方法之一
     divA.style = "width: 6px; height: 6px;" + "background: black; border-radius: 3px;" 
+ "position: absolute; left: " + (x-3)+"px;"+"top: "+(y-3)+"px;"

此种方式添加的为 行内 样式

  1. 使用div.onmousemove作为画笔时的一个问题:mousemove 的触发是比较明显的离散的,如下图:
    js-18-01.png
    左右为鼠标慢速移动时,中间为快速移动时;也就是说 div 中的 mousemove 事件作为画笔有问题。
    如何解决?????
    此处引入一个新的 html 标签 <canvas>
  1. <canvas>标签

<canvas id="tutorial" width="150" height="150"></canvas>

<canvas> 看起来和 <img> 元素很相像,唯一的不同就是它并没有 src 和 alt 属性。实际上,<canvas> 标签只有两个属性—— widthheight。这些都是可选的,并且同样利用 DOMproperties 来设置。当没有设置宽度和高度的时候,canvas会初始化宽度为300像素和高度为150像素。该元素可以使用CSS来定义大小,但在绘制时图像会伸缩以适应它的框架尺寸:如果CSS的尺寸与初始画布的比例不一致,它会出现扭曲。
比如:

<canvas id="canvas" width="300px" height="300px"></canvas>

<style>
#canvas{
  height: 1000px;
}
</style>

虽然在 css 只指定了 height ,但是 width 会根据width="300px" height="300px"等比例缩放,就如 <img> 标签一样。
使用 canvas 的基本操作:

<body>
    <canvas id="canvas" width="300px" height="300px"></canvas>
    
    <script>
        var canvas = document.getElementById('canvas');

        var context = canvas.getContext('2d'); //获取 canvas 上下文
        context.fillStyle = 'red';
        context.fillRect (10, 10, 55, 50);
    </script>
</body>
-----------------------
#canvas{
    background-color: burlywood;
    display: block; //貌似没啥效果
    height: 100vh; //不建议使用 css 设定宽高,会等比例缩放
}
js-18-02.png
上一篇 下一篇

猜你喜欢

热点阅读