canvas 도형 검증 코드 구현
25890 단어 CSS
<canvas id="canvas_code"> </canvas>
<script>
// canvas
(function(){
function Gcode(el, option) {
this.el = typeof el === 'string' ? document.querySelector(el) : el;
this.option = option;
this.init();
}
Gcode.prototype = {
constructor: Gcode,
init: function() {
if(this.el.getContext) {
isSupportCanvas = true;
var ctx = this.el.getContext('2d'),
//
cw = this.el.width = this.option.width || 200,
ch = this.el.height = this.option.height || 40,
textLen = this.option.textLen || 6,
lineNum = this.option.lineNum || 4;
var text = this.randomText(textLen);
this.onClick(ctx, textLen, lineNum, cw, ch);
this.drawLine(ctx, lineNum, cw, ch);
this.drawText(ctx, text, ch);
}
},
onClick: function(ctx, textLen, lineNum, cw, ch) {
var _ = this;
this.el.addEventListener('click', function(){
text = _.randomText(textLen);
_.drawLine(ctx, lineNum, cw, ch);
_.drawText(ctx, text, ch);
}, false)
},
//
drawLine: function(ctx, lineNum, maxW, maxH) {
ctx.clearRect(0, 0, maxW, maxH);
for(var i=0; i < lineNum; i++) {
var dx1 = Math.random()* maxW,
dy1 = Math.random()* maxH,
dx2 = Math.random()* maxW,
dy2 = Math.random()* maxH;
ctx.strokeStyle = 'rgb(' + 255*Math.random() + ',' + 255*Math.random() + ',' + 255*Math.random() + ')';
ctx.beginPath();
ctx.moveTo(dx1, dy1);
ctx.lineTo(dx2, dy2);
ctx.stroke();
}
},
//
drawText: function(ctx, text, maxH) {
var len = text.length;
for(var i=0; i < len; i++) {
var dx = 30 * Math.random() + 30* i,
dy = Math.random()* 5 + maxH/2;
ctx.fillStyle = 'rgb(' + 255*Math.random() + ',' + 255*Math.random() + ',' + 255*Math.random() + ')';
ctx.font = '30px Helvetica';
ctx.textBaseline = 'middle';
ctx.fillText(text[i], dx, dy);
}
},
//
randomText: function(len) {
var source = ['a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'o', 'p',
'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z'];
var result = [];
var sourceLen = source.length;
for(var i=0; i< len; i++) {
var text = this.generateUniqueText(source, result, sourceLen);
result.push(text)
}
return result.join('')
},
//
generateUniqueText: function(source, hasList, limit) {
var text = source[Math.floor(Math.random()*limit)];
if(hasList.indexOf(text) > -1) {
return this.generateUniqueText(source, hasList, limit)
}else {
return text
}
}
}
new Gcode('#canvas_code', {
lineNum: 6
})
})();
</script>
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
【Grunt】 복수의 CSS, JavaScript 파일을 minfy한다여러 CSS, JavaScript 파일을 Grunt를 사용하여 단번에 각각 하나의 파일로 minfy합니다. ① Gruntfile 작성 ② package.json 쓰기 ④ html CSS, JavaScript 지정 부...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.