导出、事件 API

API 描述
toDataURL() canvas 元素上的方法,将画布导出为图像
ctx.isPointInPath(x, y) 判断在当前路径中是否包含检测点,此方法只作用于最新画出的 canvas 图像

案例:将画布导出为图像

  1. 示例代码

    window.onload = function () {
        var canvas = document.querySelector("#canvas");
        if (canvas.getContext) {
            var ctx = canvas.getContext("2d");
    
            ctx.fillRect(0, 0, 199, 199);
            var result = canvas.toDataURL(); // 生成 base64 格式的文件
    
            const img = new Image();
            img.src = result;
            document.body.append(img);
        }
    }
    
  2. 效果展示

案例:事件操作

  1. 示例代码

    window.onload = function () {
        var canvas = document.querySelector("#canvas");
        if (canvas.getContext) {
            var ctx = canvas.getContext("2d");
    
            ctx.beginPath();
            ctx.fillStyle = "pink";
            ctx.arc(100, 100, 50, 0, 360 * Math.PI / 180);
            ctx.fill();
    
            moveTo(200, 200)
            ctx.beginPath();
            ctx.fillStyle = "#000";
            ctx.arc(180, 100, 50, 0, 360 * Math.PI / 180);
            ctx.fill();
    
            canvas.onclick = function (ev) {
                ev = ev || event;
                var x = ev.clientX - canvas.offsetLeft;
                var y = ev.clientY - canvas.offsetTop;
                if (ctx.isPointInPath(x, y)) {
                    alert('当前路径包含检测点...');
                }
            }
        }
    }
    
  2. 效果展示

打赏作者
您的打赏是我前进的动力
微信
支付宝
评论

中午好👏🏻,我是 ✍🏻   疯狂 codding 中...

粽子

这有关于前端开发的技术文档和你分享。

相信你可以在这里找到对你有用的知识和教程。

了解更多

目录

  1. 1. 导出、事件 API
  2. 2. 案例:将画布导出为图像
  3. 3. 案例:事件操作