canvas画图写文字,有0.5像素左右的位置偏差,无解决办法,希望有知道问题的大神告知一下

提示:canvas画图写文字

文章目录

  • 前言
  • 一、写文字
  • 总结


前言

一、写文字

test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>canvas跟随鼠标移动画透明线</title>
    <style>
        div,canvas,img{
            user-select: none;
        }
        .my_canvas,.bg_img{
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%,-50%);
        }
        .cf{
            content: '';
            display: block;
            overflow: hidden;
            clear: both;
        }
        .fl{
            float: left;
        }
        .fr{
            float: right;
        }
        .bg_img{
            width: 674px;
            height: 495px;
            background: #ddd;
        }
        .img_tools{
            position: absolute;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            border: 1px solid #eee;
            border-radius: 64px;
            height: 64px;
            line-height: 64px;
            box-sizing: border-box;
            padding: 15px 20px 0;
        }
        .img_tool{
           height: 32px;
           line-height: 32px;
           color: #000;
           font-size: 14px;
           text-align: center;
           width: 80px;
           border: 1px solid #ddd;
           border-radius: 32px;
           margin-right: 10px;
           cursor: pointer;
           position: relative;
        }
        .img_tool_active{
            color: #409EFF;
            border: 1px solid #409EFF;
        }
        .show_history{
            position: absolute;
            bottom:0;
            left: 50%;
            transform: translateX(-50%);
        }
        .show_history>img{
            width: 120px;
            margin-right: 10px;
            border: 1px solid #eee;
            border-radius: 4px;
        }
        .canvas_text{
            width: 120px;
            height: 32px;
            line-height: 32px;
            position: absolute;
            top: 0;
            left: 0;
            border: 1px solid #c0c0c0;
            border-radius: 4px;
            font-size: 16px;
            outline: none;
            background: none;
            display: none;
            font-family: Arial, Helvetica, sans-serif;
            padding-left: 0;
            letter-spacing: 0;
        }
    </style>
</head>
<body>
    <div class="bg_img"></div>
    <canvas id="myCanvasBot" class="my_canvas" width="674" height="495"></canvas>
    <canvas id="myCanvasTop" class="my_canvas" width="674" height="495"></canvas>
    <div class="img_tools cf">
        <div class="img_tool img_tool_active fl" onclick="changeType('curve',this)">涂鸦</div>
        <div class="img_tool fl" onclick="changeType('line',this)">直线</div>
        <div class="img_tool fl" onclick="changeType('rect',this)">矩形</div>
        <div class="img_tool fl" onclick="changeType('ellipse',this)">圆形</div>
        <div class="img_tool fl" onclick="changeType('eraser',this)">橡皮擦</div>
        <div class="img_tool fl" onclick="changeType('revoke',this)">撤销</div>
        <div class="img_tool fl" onclick="changeType('restore',this)">恢复</div>
        <div class="img_tool fl" onclick="changeType('text',this)">文字</div>
    </div>
    <input id="canvasText" autofocus class="canvas_text" type="text">
    <div id="showHistory" class="show_history"></div>
    <script>
        const canvasWidth = 674;
        const canvasHeight = 495;
        //底层canvas
        const botCan = document.getElementById('myCanvasBot');
        //顶层canvas
        const topCan = document.getElementById('myCanvasTop');
        //底层画布
        const botCtx = botCan.getContext('2d');
        //顶层画布
        const topCtx = topCan.getContext('2d');
        topCtx.lineCap = 'round';
        topCtx.lineJoin = 'round';
        //鼠标是否按下  是否移动
        let isDown = false,isMove = false;
        //鼠标是否在canvas上抬起
        let isCanUp = false;
        //需要画图的轨迹
        let drawPoints = [];
        //起始点x,y
        let startPoint = {
            x:0,
            y:0
        };
        //图片历史
        let historyList = [];
        //空历史
        historyList.push(new Image())
        //当前绘画历史index
        let historyIndex = -1;
        //icon历史
        // let partHistory = [];
        //操作类型
        let drawType = 'curve';
        //画线宽度
        const lineWidth = 10;
        //文字大小
        const fontSize = 16;
        //画线颜色
        let strokeStyle = 'rgba(255,0,0,0.6)';
        //文字输入框init
        const canvasText = document.getElementById('canvasText');
        canvasText.style.display = 'none';
        canvasText.style.lineHeight = '32px';
        canvasText.style.height = '32px';
        canvasText.style.display = 'none';
        canvasText.style.color = 'none';
        canvasText.addEventListener('blur',()=>{
            topCtx.font = fontSize + 'px Arial, Helvetica, sans-serif';
            let h = parseFloat(canvasText.style.height);
            topCtx.fillText(canvasText.value, startPoint.x+1, startPoint.y+h/2+fontSize/2-1);
            canvasText.style.display = 'none';
            canvasText.value = '';
            topToBot();
        })
        //起始点x,y
        let textPoint = {
            x:0,
            y:0
        };
        //鼠标按下
        const mousedown = (e)=>{
            isDown = true;
            let x = (e||window.event).offsetX;
            let y = (e||window.event).offsetY;
            if(canvasText.style.display == 'none')startPoint = {x,y};
            if(drawType == 'text'){
                textPoint = {
                    x:x+topCan.offsetLeft-canvasWidth/2,
                    y:y+topCan.offsetTop-canvasHeight/2
                };
                // canvasText.style.height = 32 + 'px';
                canvasText.style.top = textPoint.y+'px';
                canvasText.style.left = textPoint.x+'px';
                canvasText.style.display = 'block';
                canvasText.style.fontSize = fontSize + 'px';
                canvasText.style.color = strokeStyle;
                setTimeout(()=>{
                    canvasText.focus();
                },100)
            }
            if(drawType == 'curve'){
                drawPoints = [];
                drawPoints.push([{x,y}]);
            }
            topCtx.strokeStyle = strokeStyle;
            topCtx.fillStyle = strokeStyle;
            topCtx.lineWidth = lineWidth;
            topCtx.beginPath();
            topCtx.moveTo(x,y);
        }
        //鼠标移动
        const mousemove = (e)=>{
            let x = (e||window.event).offsetX;
            let y = (e||window.event).offsetY;
            if(isDown){
                isMove = true;
                switch(drawType){
                    case 'curve':
                        drawCurve(x,y);
                        break;
                    case 'line':
                        drawLine(x,y);
                        break;
                    case 'eraser':
                        drawEraser(x,y);
                        break;
                    case 'rect':
                        drawRect(x,y);
                        break;
                    case 'ellipse':
                        drawEllipse(x,y);
                        break;
                }
            }
        }
        //鼠标抬起
        const mouseup = (e)=>{
            isCanUp = true;
            if(isDown){
                // topCan内容画到botCan上
                if(drawType!='text')topToBot();
            }
        }
        //topCan内容画到botCan上
        const topToBot = ()=>{
            //把topCan画布生成图片
            let img = new Image();
            img.src = topCan.toDataURL('image/png');
            img.onload = ()=>{
                // partHistory.push(img);
                //添加到botCtx画布
                botCtx.drawImage(img,0,0);
                let historyImg = new Image();
                historyImg.src = botCan.toDataURL('image/png');
                historyImg.onload = ()=>{
                    //添加到历史记录
                    historyList.push(historyImg);
                    historyIndex = historyList.length - 1;
                    let ele = document.getElementById('showHistory');
                    let html='';
                    for(let i=0;i<historyList.length;i++){
                        if(historyList[i].src)html += `<img src="${historyList[i].src}" alt="">`
                    }
                    ele.innerHTML = html;
                }
                //清除topCtx画布
                topCtx.clearRect(0,0,canvasWidth,canvasHeight);
                //botCan画完之后,重置canvas的mouseup isCanUp
                if(isCanUp)isCanUp=false;
            }
            drawPoints = [];
            isDown = false;
            isMove = false;
        }
        //画椭圆形
        const drawEllipse = (x,y)=>{
            //清除topCtx画布
            topCtx.clearRect(0,0,canvasWidth,canvasHeight);
            topCtx.beginPath();
            // 椭圆
            topCtx.ellipse((x+startPoint.x)/2, (y+startPoint.y)/2, Math.abs((x-startPoint.x)/2), Math.abs((y-startPoint.y)/2),0,0, Math.PI*2,true);
            topCtx.stroke();
        }
        //画矩形
        const drawRect = (x,y)=>{
            //清除topCtx画布
            topCtx.clearRect(0,0,canvasWidth,canvasHeight);
            topCtx.beginPath();
            // 矩形
            topCtx.rect(startPoint.x, startPoint.y, x-startPoint.x, y - startPoint.y);
            topCtx.stroke();
        }
        //橡皮擦
        const drawEraser = (x,y)=>{
            //橡皮擦圆形半径
            const radius = lineWidth/2;
            botCtx.beginPath(); 
            for(let i=0;i<radius*2;i++){
                //勾股定理高h
                let h = Math.abs( radius - i); //i>radius h = i-radius; i<radius  h = radius - i
                //勾股定理l
                let l = Math.sqrt(radius*radius -h*h); 
                //矩形高度
                let rectHeight = 1;
                 //矩形宽度
                let rectWidth = 2*l;
                //矩形X
                let rectX = x-l;
                //矩形Y
                let rectY = y-radius + i;

                botCtx.clearRect(rectX, rectY, rectWidth, rectHeight);
            }
        }
        //画透明度直线
        const drawLine = (x,y)=>{
            if(!isDown)return;
            //清空当前画布内容
            topCtx.clearRect(0,0,canvasWidth,canvasHeight);
            //必须每次都beginPath  不然会卡
            topCtx.beginPath();
            topCtx.moveTo(startPoint.x,startPoint.y);
            topCtx.lineTo(x,y);
            topCtx.stroke();
        }
        //画带透明度涂鸦
        const drawCurve = (x,y)=>{
            drawPoints.push({x,y});
            //清空当前画布内容
            topCtx.clearRect(0,0,canvasWidth,canvasHeight);
            //必须每次都beginPath  不然会卡
            topCtx.beginPath();
            topCtx.moveTo(drawPoints[0].x,drawPoints[0].y);
            for(let i=1;i<drawPoints.length;i++){
                topCtx.lineTo(drawPoints[i].x,drawPoints[i].y);
            }
            topCtx.stroke();
        }
        //切换操作
        const changeType = (type,that)=>{
            // if(drawType == type) return;
            let tools = document.getElementsByClassName('img_tool');
            for(let i=0;i<tools.length;i++){
                let ele = tools[i];
                if(ele.classList.contains('img_tool_active'))ele.classList.remove('img_tool_active'); //ele.removeClassName('img_tool_active');
            }
            that.classList.add('img_tool_active');
            drawType = type;
            //撤销
            if(drawType == 'revoke'){
                if(historyIndex>0){
                    historyIndex--;
                    drawImage(historyList[historyIndex]);
                }
            //恢复
            }else if(drawType == 'restore'){
                if(historyIndex<historyList.length - 1){
                    historyIndex++;
                    drawImage(historyList[historyIndex]);
                }
            }
        }
        const drawImage = (img)=>{
            botCtx.clearRect(0,0,canvasWidth,canvasHeight);
            botCtx.drawImage(img,0,0);
        }

        //canvas添加鼠标事件
        topCan.addEventListener('mousedown',mousedown);
        topCan.addEventListener('mousemove',mousemove);
        topCan.addEventListener('mouseup',mouseup);
        //全局添加鼠标抬起事件
        document.addEventListener('mouseup',(e)=>{
            let x = (e||window.event).offsetX;
            let y = (e||window.event).offsetY;
            let classList = (e.target || {}).classList || [];
            if(classList.contains('img_tool'))return;
            if(!isCanUp){
                if(drawType == 'line'){
                    let clientX = topCan.getBoundingClientRect().x;
                    let clientY = topCan.getBoundingClientRect().y;
                    drawLine(x-clientX,y-clientY);
                }
                // topCan内容画到botCan上
                topToBot();
            }
        });
        //全局添加鼠标移动事件
        document.addEventListener('mousemove',(e)=>{
            if(isMove)return isMove = false;
            let x = (e||window.event).offsetX;
            let y = (e||window.event).offsetY;
            if(drawType == 'line'){
                let clientX = topCan.getBoundingClientRect().x;
                let clientY = topCan.getBoundingClientRect().y;
                drawLine(x-clientX,y-clientY);
            }
        });
    </script>
</body>
</html>

在这里插入图片描述
在这里插入图片描述

文字会有0.5像素左右的位置偏差,尝试用0.1-0.9等小数均不可以,希望有知道问题的大神告知一下,谢谢

总结

踩坑路漫漫长@~@

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/491228.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Fragment 与 ViewPager的联合应用(2)

5.创建底部布局bottom_layout <LinearLayout xmlns:android"http://schemas.android.com/apk/res/android"android:orientation"horizontal"android:layout_width"match_parent"android:layout_height"55dp"android:background&qu…

【算法】求最大公约数和最小公倍数

题目 输入两个数&#xff08;空格隔开&#xff09;分2行输出他们的最大公因数和最小公倍数 原理 辗转相除法计算最大公约数 将两个数中较大的数除以较小的数&#xff0c;并将较小的数作为除数&#xff0c;较大的数作为被除数。计算余数。若余数为零&#xff0c;则较小的数即…

深入探索MySQL高阶查询语句的艺术与实践

目录 引言 一、条件查询 &#xff08;一&#xff09;比较运算符查询 1.使用匹配符号查询 2.范围查找 &#xff08;二&#xff09;逻辑运算符 二、关键字排序 三、分组与聚合函数 四、限制查询 五、别名 &#xff08;一&#xff09;设置列别名 &#xff08;二&#x…

Dockerfile和Docker-compose

一、概述 Dockerfile和Docker Compose是用于构建和管理 Docker 容器的两个工具&#xff0c;但它们的作用和使用方式不同。 Dockerfile Dockerfile 是一个文本文件&#xff0c;用于定义 Docker 镜像的构建规则。它包含一系列指令&#xff0c;如 FROM&#xff08;指定基础镜像…

python(django)之单一接口管理功能后台开发

1、创建数据模型 在apitest/models.py下加入以下代码 class Apis(models.Model):Product models.ForeignKey(product.Product, on_deletemodels.CASCADE, nullTrue)# 关联产品IDapiname models.CharField(接口名称, max_length100)apiurl models.CharField(接口地址, max_…

uniapp微信小程序_computed_计算BMI

一、computed的用法还有它是什么&#xff1f; 首先它叫计算属性&#xff0c;顾名思义他是用来计算属性&#xff0c;计算你在data模板上定义的属性&#xff08;其实在插值表达式也能直接计算但是首先太长了在{{}}里面写那么多不好看&#xff0c;还有其他特点我在下面一起说&…

jupyter notebook导出含中文的pdf(LaTex安装和Pandoc、MiKTex安装)

用jupyter notebook导出pdf时&#xff0c;因为报错信息&#xff0c;需要用到Tex nbconvert failed: xelatex not found on PATH, if you have not installed xelatex you may need to do so. Find further instructions at https://nbconvert.readthedocs.io/en/latest/install…

nacos集群搭建实战

集群结构图 初始化数据库 Nacos默认数据存储在内嵌数据库Derby中&#xff0c;不属于生产可用的数据库。官方推荐的使用mysql数据库&#xff0c;推荐使用数据库集群或者高可用数据库。 首先新建一个数据库&#xff0c;命名为nacos&#xff0c;而后导入下面的SQL&#xff08;直…

苹果Find My产品需求增长迅速,伦茨科技ST17H6x芯片供货充足

苹果的Find My功能使得用户可以轻松查找iPhone、Mac、AirPods以及Apple Watch等设备。如今Find My还进入了耳机、充电宝、箱包、电动车、保温杯等多个行业。苹果发布AirTag发布以来&#xff0c;大家都更加注重物品的防丢&#xff0c;苹果的 Find My 就可以查找 iPhone、Mac、Ai…

Qt 图形视图 /图形视图框架坐标系统的设计理念和使用方法

文章目录 概述Qt 坐标系统图形视图的渲染过程Item图形项坐标系Scene场景坐标系View视图坐标系map坐标映射场景坐标转项坐标视图坐标转图形项坐标图形项之间的坐标转换 其他 概述 The Graphics View Coordinate System 图形视图坐标系统是Qt图形视图框架的重要组成部分&#xf…

vue指令相关

vue中有很多的指令像v-on、v-model、v-bind等是我们开发中常用的 常用指令 v-bind 单向绑定解析表达式 v-model 双向数据绑定 v-for 遍历数组/对象/字符串 v-on 绑定事件监听,可简写为@ v-show 条件渲染(动态控制节点是否存展示) v-if 条件渲染(动态控制节点是否存存在) v…

R 生存分析3:Cox等比例风险回归及等比例风险检验

虽然Kaplan-Meier分析方法目前应用很广&#xff0c;但是该方法存在一下局限: 对于一些连续型变量&#xff0c;必须分类下可以进行生存率对比 是一种单变量分析&#xff0c;无法同时对多组变量进行分析 是一种非参数分析方法&#xff0c;必须有患者个体数据才能进行分析 英国…

鸿蒙开发-UI-交互事件-焦点事件

鸿蒙开发-UI-图形-绘制几何图形 鸿蒙开发-UI-图形-绘制自定义图形 鸿蒙开发-UI-图形-页面内动画 鸿蒙开发-UI-图形-组件内转场动画 鸿蒙开发-UI-图形-弹簧曲线动画 鸿蒙开发-UI-交互事件-通用事件 鸿蒙开发-UI-交互事件-键鼠事件 文章目录 前言 一、基本概念 二、走焦规则 三、…

android_uiautomator元素定位

通过UIAUTOMATOR的text属性定位到元素&#xff0c;并打印文本from appium import webdriver from appium.webdriver.common.appiumby import AppiumBy import time # For W3C actions from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriv…

小程序富文本图片宽度自适应

解决这个问题 创建一个util.js文件,图片的最大宽度设置为100%就行了 function formatRichText(html) {let newContent html.replace(/\<img/gi, <img style"max-width:100%;height:auto;display:block;");return newContent; }module.exports {formatRichT…

2024.3.26

头文件: #ifndef WIDGET_H #define WIDGET_H#include <QWidget> #include <QTime> #include <QTimerEvent> #include <QTimer> #include <QtTextToSpeech>QT_BEGIN_NAMESPACE namespace Ui { class Widget; } QT_END_NAMESPACEclass Widget : p…

centos创建svn库步骤

1.切换root用户 1、设置root用户的密码&#xff1a; sudo passwd root 2、切换到root用户权限 su 3、切换回个人用户权限 exit 2.用root用户执行yum install -y subversion 3.创建文件夹mkdir -p /data/svn/repository 4.创建SVN 版本库 5.输入命令&#xff1a; svnadmin creat…

第 1 章.提示词:开启AI智慧之门的钥匙

什么是提示词&#xff1f; 提示词&#xff0c;是引导语言模型的指令&#xff0c;让用户能够驾驭模型的输出&#xff0c;确保生成的文本符合需求。 ChatGPT&#xff0c;这位文字界的艺术大师&#xff0c;以transformer架构为基石&#xff0c;能轻松驾驭海量数据&#xff0c;编织…

Java 与 Go:时间函数

在软件开发中&#xff0c;时间和日期函数是必不可少的组成部分&#xff0c;而 Java 和 Go 是两种备受欢迎的编程语言&#xff0c;它们在时间和日期函数方面有着各自独特的特性。本文将对比 Java 和 Go 在时间和日期函数上的优劣&#xff0c;并探讨它们的用法和适用场景。 Java…

2024品牌私域运营:「去中心化」正在成为企业决胜关键

越来越多的品牌选择以DTC模式与消费者互动和销售。通过与消费者建立紧密联系&#xff0c;不仅可提供更具成本效益的规模扩张方式&#xff0c;还能控制品牌体验、获取宝贵的第一方数据并提升盈利能力。许多企业采取的DTC私域策略以交易为中心的方法往往导致了成本上升和运营复杂…
最新文章