javascript - 制作模糊形状的 HTML Canvas

标签 javascript html canvas html5-canvas

我想使用 HTML 制作简单的形状。 但是形状需要很大。 并且 Canvas 是全屏的

示例:http://jsfiddle.net/xLgg43s9/1/embedded/result/

代码:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
* { margin: 0; padding: 0;}

body, html { height:100%; }

#canvas {
    position:absolute;
    width:100%;
    height:100%;
}
</style>
</head>

<body>
<canvas id="canvas">
</canvas>
<script>
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.fillStyle = "#000";
var w=canvas.width;
var h=canvas.height;
ctx.fillRect(0,0,w,h);
ctx.fillStyle="#fff";
ctx.beginPath();
var a=w/2;
var b=0;
ctx.arc(a,b,20,0,Math.PI,false);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.beginPath();
ctx.fillStyle="red";
ctx.fillRect(0,0,10,100);
ctx.stroke();
ctx.save();

ctx.translate(240, 120);

ctx.rotate(Math.PI / 4); // 45 degrees

ctx.fillStyle = "yellow";
ctx.fillRect(-40, -40, 20, 20);

ctx.restore();

</script>
</body>
</html>

请修复它。

最佳答案

不要通过 CSS 设置 Canvas 的大小,它会拉伸(stretch) Canvas 元素,而不是实际使 Canvas 变大。

改用 HTML 属性:

<canvas id="canvas" width="500" height="500"></canvas>

现在,由于您想将 Canvas 设置为 100% 宽度/高度,这些预设属性不会为您解决问题,您将不得不使用一些 JS:

var canvas = document.getElementById("canvas");
canvas.width  = window.innerWidth;
canvas.height = window.innerHeight;
var ctx=canvas.getContext("2d");
// etc...

如果您想在调整窗口大小时调整 Canvas 大小,我建议您查看 this answer.

关于javascript - 制作模糊形状的 HTML Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27705977/

相关文章:

javascript - ajax 不能与 django 一起使用

javascript - 如何在node js中将cassandra数据库查询结果读取到UI

css - 没有 Javascript 的 SVG 链接和 PNG 回退

java - 无法让 Canvas/CanvasLayer 在 Playn 中工作

javascript - 在导入函数中访问 this.props

javascript - 为什么对象的值在函数调用中被捕获?

javascript - 当资源发布到根文件夹时,Animate CC HTML5 横幅不起作用

javascript - CSS全局变量随js变化

javascript - 使用 d3.js 和 HTML5 Canvas(不是 SVG)的鼠标事件

javascript - 指定 infoVis JIT 图中节点之间的最小距离