在不使用canvas.rotate的情况下在画布中绘制旋转的圆角矩形

如何解决在不使用canvas.rotate的情况下在画布中绘制旋转的圆角矩形

我用quadraticCurveTo在画布上绘制了圆角矩形

enter image description here

function roundRect(x0,y0,x1,y1,r,color) {
    var w = x1 - x0;
    var h = y1 - y0;
    if (r > w/2) r = w/2;
    if (r > h/2) r = h/2;
    context.beginPath();
    context.moveTo(x1 - r,y0);
    context.quadraticCurveTo(x1,y0 + r);
    context.lineTo(x1,y1-r);
    context.quadraticCurveTo(x1,x1 - r,y1);
    context.lineTo(x0 + r,y1);
    context.quadraticCurveTo(x0,x0,y1 - r);
    context.lineTo(x0,y0 + r);
    context.quadraticCurveTo(x0,x0 + r,y0);
    context.closePath();
    context.fillStyle = color;
    context.fill();
}

现在我得到了(x1,y1),(x2,y2),(x3,y3),(x4,y4)四个点的矩形, 并希望在画布中绘制旋转的圆角矩形而不使用canvas.rotate()

enter image description here

  function roundRect(x1,x2,y2,x3,y3,x4,y4,color) {
    var w = x4 - x1;
    var h = y4 - y1;
    if (r > w/2) r = w/2;
    if (r > h/2) r = h/2;
    context.beginPath();
    context.moveTo(x2 - r,y2);
    context.quadraticCurveTo(x2,y2 + r);
    context.lineTo(x4,y4-r);
    context.quadraticCurveTo(x4,x4 - r,y4);
    context.lineTo(x3 + r,y3);
    context.quadraticCurveTo(x3,y3 - r);
    context.lineTo(x1,y1 + r);
    context.quadraticCurveTo(x1,x1 + r,y1);
    context.closePath();
    context.fillStyle = color;
    context.fill();
  }

此角的代码位置错误,是否可以使用x1-x4,y1-y4而不使用canvas.rotate()绘制旋转的圆角矩形?我确定我的x1-x4,y1-y4可以正常工作。

解决方法

变换坐标

要旋转框,您需要在每个点上应用旋转矩阵。

矩阵

矩阵定义了x轴(顶部)和y轴(像素的右侧,包括比例,或者像素有多大)以及原点的位置(坐标{x:0,y:0})>

    const xAx = Math.cos(angle) * scale;  // scale is the size of a pixel 
    const xAy = Math.sin(angle) * scale;
    const yAx = Math.cos(angle + Math.PI / 2) * scale;  // Y axis 90 deg CW from x axis
    const yAy = Math.sin(angle + Math.PI / 2) * scale;

    matrix[0] = xAx;  // x part of x axis
    matrix[1] = xAy;  // y part of x axis
    matrix[2] = yAx;  // x part of y axis
    matrix[3] = yAy;  // y part of y axis
    matrix[4] = 0;    // origin x
    matrix[5] = 0;    // origin y

转型

将坐标xy转换为txty ...

   const x = ?
   const y = ?
   var tx,ty;

...您首先将其单独移动到x轴...

   tx = x * matrix[0]
   ty = x * matrix[1]

...可以同时沿x轴缩放它。然后沿y轴移动并缩放。

   tx += y * matrix[2]
   ty += y * matrix[3]

然后移至原点

   tx += matrix[4]
   ty += matrix[5]

此变换将坐标从局部空间移动到世界空间(或在2D世界空间中通常称为视图)

本地空间

旋转形状时,需要选择一个要围绕其旋转的点,例如中心或一个角。

为此,您需要定义相对于旋转点的形状(在形状的局部空间中)。例如,如果要围绕中心旋转框,则将左上角和右下角点定义为与零相等的距离,例如[-100,-50][100,50]

要在某个角上旋转,请相对于该角放置盒子。例如,框的左上方是[0,0][200,100]

通过设置矩阵的原点(旋转中心将在画布上的位置)将形状放置在世界空间中

示例

如果我们知道比例尺是均匀的(x和y轴比例相同,并且x和y轴始终彼此成90度),则可以简化上述矩阵计算。

该示例使用数组保存矩阵,函数

  • transformPoint将矩阵应用于一个点
  • setOrigin设置变换原点(旋转点在画布上的位置)
  • setRotation设置x和y轴的方向
  • setScale未在示例中使用。设置变换的比例。注意在此示例中,setScale之后必须调用setRotation
  • setTransform未在示例中使用。一次拨打以上3个电话吗
  • roundRect绘制形状,并在局部空间中为其指定框的左上角和右下角坐标。它将拐角半径限制为最小尺寸,该尺寸将适合并仍保持(由于贝塞尔曲线永远不会变圆)圆角

有两个框来演示如何更改旋转中心。一个围绕其中心旋转,另一个围绕左上角旋转。

第三个框(红色)表明没有理由手动变换该框,使用2D API变换是相同的,但简单得多,并且很多更快

requestAnimationFrame(update);
const ctx = canvas.getContext("2d");

const matrix = [1,1,0];
function transfromPoint(x,y) {
    const m = matrix;
    return [x * m[0] + y * m[2] + m[4],x * m[1] + y * m[3] + m[5]];
}
function setOrigin(x,y) {
    matrix[4] = x;
    matrix[5] = y;
}
function setRotation(angle) {
    const ax = Math.cos(angle);
    const ay = Math.sin(angle);
    matrix[0] = ax;
    matrix[1] = ay;
    matrix[2] = -ay;
    matrix[3] = ax;
}
function setScale(scale) {
    matrix[0] *= scale;
    matrix[1] *= scale;
    matrix[2] *= scale;
    matrix[3] *= scale;
}
function setTransform(ox,oy,rot,scale) {
    const ax = Math.cos(rot) * scale;
    const ay = Math.sin(rot) * scale;
    matrix[0] = ax;
    matrix[1] = ay;
    matrix[2] = -ay;
    matrix[3] = ax;
    matrix[4] = ox;
    matrix[5] = oy;
}

function roundRect(x1,y1,x2,y2,r,color = "#000",lineWidth = 2) {
    ctx.strokeStyle  = color;
    ctx.lineWidth = lineWidth;
    const min = Math.min(Math.abs(x1 - x2),Math.abs(y1 - y2));
    r = r > min ? min / 2 : r;
    ctx.beginPath();
    ctx.moveTo(...transfromPoint(x2 - r,y1));
    ctx.quadraticCurveTo(...transfromPoint(x2,y1),...transfromPoint(x2,y1 + r));
    ctx.lineTo(...transfromPoint(x2,y2 - r));
    ctx.quadraticCurveTo(...transfromPoint(x2,y2),...transfromPoint(x2 - r,y2));
    ctx.lineTo(...transfromPoint(x1 + r,y2));
    ctx.quadraticCurveTo(...transfromPoint(x1,...transfromPoint(x1,y2 - r));
    ctx.lineTo(...transfromPoint(x1,y1 + r));
    ctx.quadraticCurveTo(...transfromPoint(x1,...transfromPoint(x1 + r,y1));
    ctx.closePath();
    ctx.stroke();
}
function roundRectAPITransform(x1,color = "#F00",lineWidth = 2) {
    ctx.strokeStyle = color;
    ctx.lineWidth = lineWidth;
    const min = Math.min(Math.abs(x1 - x2),Math.abs(y1 - y2));
    r = r > min ? min / 2 : r;
    ctx.beginPath();
    ctx.moveTo(x2 - r,y1);
    ctx.quadraticCurveTo(x2,y1 + r);
    ctx.lineTo(x2,y2 - r);
    ctx.quadraticCurveTo(x2,x2 - r,y2);
    ctx.lineTo(x1 + r,y2);
    ctx.quadraticCurveTo(x1,x1,y2 - r);
    ctx.lineTo(x1,y1 + r);
    ctx.quadraticCurveTo(x1,x1 + r,y1);
    ctx.closePath();
    ctx.stroke();
}
function update(time) {
    ctx.clearRect(0,ctx.canvas.width,ctx.canvas.height);

    // around center
    setOrigin(100,100);
    setRotation(time * Math.PI / 2000); // one rotation every 4 seconds
    roundRect(-60,-35,60,35,15);

    // around top right corner
    setOrigin(300,100);
    setRotation(-time * Math.PI / 2000); // one rotation every 4 seconds
    roundRect(-60,5);

    // red box using API
    ctx.setTransform(1,200,100);
    ctx.rotate(-time * Math.PI / 4000) // once every 8 seconds;
    roundRectAPITransform(-30,-15,30,15,12);
    ctx.setTransform(1,0); // restore default

    requestAnimationFrame(update);
}
  
<canvas id="canvas" width="400" height="200"></canvas>

更新

评论

您不想旋转矩形,已经旋转了。

以下函数将圆角添加到旋转矩形

// MUST BE RECTANGULAR!!
function roundRectangle(x1,x3,y3,x4,y4,color) {

    // get top and left edge vectors and lengths
    var tx = x2 - x1;
    var ty = y2 - y1;
    const td = (tx * tx + ty * ty) ** 0.5;
    var lx = x3 - x1;
    var ly = y3 - y1;
    const ld = (lx * lx + ly * ly) ** 0.5;

    // Constrain corner radius
    const min = Math.min(td,ld) / 2;
    r = r > min ? min  : r;
    
    // Normalize vectors to length of corner radius
    tx *= r / td;
    ty *= r / td;
    lx *= r / ld;
    ly *= r / ld;
    
    // draw rotated retangle
    ctx.fillStyle = color;
    ctx.beginPath();
    ctx.lineTo(x2 - tx,y2 - ty);
    ctx.quadraticCurveTo(x2,x2 + lx,y2 + ly);
    ctx.lineTo(x4 - lx,y4 - ly);
    ctx.quadraticCurveTo(x4,x4 - tx,y4 - ty);
    ctx.lineTo(x3 + tx,y3 + ty);
    ctx.quadraticCurveTo(x3,x3 - lx,y3 - ly);
    ctx.lineTo(x1 + lx,y1 + ly);
    ctx.quadraticCurveTo(x1,x1 + tx,y1 + ty);
    ctx.fill();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-