canvas中如何实现圆形背景图片?

canvas中如何实现圆形背景图片?,第1张

实现画布橡皮擦有两个思路:

1.用clearRect(x,

y, width, height)来实现,x, y 矩形的左上角的坐标。width,

height 矩形的尺寸。clearRect()

方法擦除了指定的矩形,并且用一个透明的颜色填充

它。我们用这个可以实现画布擦除,但它是矩形的。我也没有想出什么好的方法,所以

弃之,采用第二种方法!

2、第二种方法就是画出一个圆,此圆为透明,然后使相交部分变成透明的就ok了。

这里就用到了canvas的globalCompositeOperation函数了,简单来说,Composite(组

合),就是对你在绘图中,后绘制图形与先绘制的图形之间的组合显示效果,比如在国画中,

你先画一笔红色,再来一笔绿色,相交的部分是一种混色,而在油画中,绿色就会覆盖掉相交

部分的红色,这在程序绘图中的处理就是Composite,Canvas

API中对应的函数就是

globalCompositeOperation,跟globalAlpha一样,这个属性是全局的,所以在使用的时

候要注意save和restore.

下面是每一个选项的说明:

source-over

默认,相交部分由后绘制图形的填充(颜色,渐变,纹理)覆盖,全部浏览器通过

source-in

只绘制相交部分,由后绘制图形的填充覆盖,其余部分透明,webkit两兄弟没有

通过

source-out

只绘制后绘制图形不相交的部分,由后绘制图形的填充覆盖,其余部分透

明,webkit两兄弟没有通过

source-atop

后绘制图形不相交的部分透明,相交部分由后绘制图形的填充覆盖,全部浏

览器通过

destination-over

相交部分由先绘制图形的填充(颜色,渐变,纹理)覆盖,全部浏览器通过

destination-in

只绘制相交部分,由先绘制图形的填充覆盖,其余部分透明,webkit两兄弟

没有通过

destination-out

只绘制先绘制图形不相交的部分,由先绘制图形的填充覆盖,其余部分透

明,全部浏览器通过

destination-atop

先绘制图形不相交的部分透明,相交部分由先绘制图形的填充覆

盖,webkit两兄弟没有通过

lighter

相交部分由根据先后图形填充来增加亮度,全部浏览器通过

darker

相交部分由根据先后图形填充来降低亮度,chrome通过,firefox官方说Firefox

3.6 / Thunderbird 3.1 /

Fennec

1.0以后版本移除这个效果-0-,why?safari看似可

以,但是无论你什么颜色,它都给填充成黑色,opera无效果

copy

只绘制后绘制图形,只有opera通过

xor

相交部分透明,全部浏览器通过

下面就是用上面的属性实现圆形橡皮擦的代码:

狠狠的点击这里-javascript

canvas画图实例(请使用支持canvas的chrome,firefox

等浏览器观看)

function

resetEraser(_x,_y,touch)

{

var

t=this

t.cxt.globalCompositeOperation

=

"destination-out"

t.cxt.beginPath()

t.cxt.arc(_x,

_y, t.eraserRadius, 0, Math.PI *

2)

t.cxt.strokeStyle =

"rgba(250,250,250,0)"//使用颜色值为白色,透明为0的颜色填充

t.cxt.fill()

t.cxt.globalCompositeOperation

= "source-over"

}

canvas提供的clearRect(x, y, width, height)方法只能清理出特定位置的矩形区域,以下代码则能实现对圆形区域的清

理,主要是利用计算圆周率时的方法,将整个圆切成一个一个细小的正方形,然后再通过clearRect(x, y, width, height)

方法将一个一个细小的正方形区域清理。

<!DOCTYPE html>

<html>

<head>

<style>

canvas{ border:1px solid black}

body{ margin:0padding:0}

</style>

</head>

<body>

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

<script>

var canvas=document.getElementById('canvas')

var context=canvas.getContext('2d')

context.beginPath()

context.fillStyle="blue"

context.arc(200,200,100,0,360*Math.PI/180)

context.fill()

function clearArc(x,y,radius){//圆心(x,y),半径radius

var calcWidth=radius-stepClear

var calcHeight=Math.sqrt(radius*radius-calcWidth*calcWidth)

var posX=x-calcWidth

var posY=y-calcHeight

var widthX=2*calcWidth

var heightY=2*calcHeight

if(stepClear<=radius){

context.clearRect(posX,posY,widthX,heightY)

stepClear+=1

clearArc(x,y,radius)

}

}

var stepClear=1//别忘记这一步

clearArc(210,230,50)

</script>

</body>

</html>

1、原始图片

2、绘制后在地图中呈现的样式

3、设置样式的函数

4、绘制

上面样式设置的函数写好后,这里就可以开始实例化vector , 将其添加到地图中去了

记录记录便于查阅


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11885070.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存