Html canvas flickering while stroking lines - javascript

<html>
<head>
<meta name="viewport" content="width=device-width">
<style>
body{
margin:0;
}
img{
display:none;
}
</style>
</head>
<body onload="Start()">
<canvas id="canvas"></canvas>
<img id="mapImg" src="Img/map.png"/>
<script>
var worker = new Worker("WebWorker.js");
var W = window.innerWidth;
var H = window.innerHeight;
var map = document.getElementById("mapImg");
var cvs = document.getElementById("canvas");
cvs.width = W;
cvs.height = H;
var ctx = cvs.getContext("2d");
var offscreenCvs = document.createElement("canvas");
offscreenCvs.width = W;
offscreenCvs.height = H;
var offscreenCtx = offscreenCvs.getContext("2d");
var mapCvs = document.createElement("canvas");
var mapCtx,mapData;
var px=25;
var py=0;
var pz=27;
var yaw=0;
var pitch=0;
var buffer=[];
function Start(){
mapCvs.width = map.width;
mapCvs.height = map.height;
mapCtx = mapCvs.getContext("2d");
mapCtx.drawImage(map,0,0);
mapData = mapCtx.getImageData(0,0,map.width,map.height);
worker.postMessage([px,py,pz,yaw,pitch,mapData]);
}
var delta = 0;
var dt = 0;
var Updated=false;
worker.onmessage = function(e){
dt = (performance.now()-delta)/1000;
buffer = e.data;
yaw+= dt*90;
if(!Updated){
requestAnimationFrame(Update);
Updated = true;
}
delta = performance.now();
worker.postMessage([px,py,pz,yaw,pitch,mapData]);
}
function Update(){
offscreenCtx.lineWidth = W/80;
var currentBuffer = buffer;
for(var dists=0; dists<80; dists++){
offscreenCtx.strokeStyle = currentBuffer[dists][0];
offscreenCtx.beginPath();
offscreenCtx.moveTo(W/80*dists,H/2-200/currentBuffer[dists][1]*H);
offscreenCtx.lineTo(W/80*dists,H/2+200/currentBuffer[dists][1]*H);
offscreenCtx.closePath();
offscreenCtx.stroke();
}
//alert(currentBuffer[60][0]);
/*offscreenCtx.strokeStyle = "rgb(255,0,0)";
offscreenCtx.beginPath();
offscreenCtx.moveTo(0,0);
offscreenCtx.lineTo(100,100);
offscreenCtx.stroke();*/
ctx.clearRect(0,0,W,H);
ctx.drawImage(offscreenCvs,0,0);
offscreenCtx.clearRect(0,0,W,H);
requestAnimationFrame(Update);
}
</script>
</body>
</html>
I'm trying to make a raycaster with color.
However, when I try to stroke lines, some lines flicker or invisible.
(red flickers,yellow is insivible)
(offscreenCtx.beginPath()
and
offscreenCtx.stroke()
is in for loop in order to change colors.)
here's my web-worker code
onmessage=function(e){
var pkg = e.data;
postMessage(Raycast(pkg[0],pkg[1],pkg[2],pkg[3],pkg[4],pkg[5]));
}
var far = 100;
function Raycast(x,y,z,yaw,pitch,mapData){
var distances=[];
var map = mapData.data;
for(var rayYaw = yaw-40;rayYaw<yaw+40;rayYaw++){
for(var l = 0;l<far;l+=1){
fx = x+Math.round(Math.sin(rayYaw/180*Math.PI)*l);
fz = z+Math.round(Math.cos(rayYaw/180*Math.PI)*l);
if(fx<0||fx>mapData.width||fz<0||fz>mapData.height){
let color = "rgb(255,255,255)";
distances.unshift([color,Math.min(Math.hypot(fx-x,fz-z),far)*100*Math.cos((rayYaw-yaw)/180*Math.PI)]);
break;
}else if(map[Math.round(fx+fz*mapData.width)*4]!=255&&map[Math.round(fx+fz*mapData.width)*4+2]!=255&&map[Math.round(fx+fz*mapData.width)*4+2]!=255){
let color = "rgb("+map[Math.round(fx+fz*mapData.width)*4]+","+map[Math.round(fx+fz*mapData.width)*4+1]+","+map[Math.round(fx+fz*mapData.width)*4+2]+")";
distances.unshift([color,Math.min(Math.hypot(fx-x,fz-z),far)*100*Math.cos((rayYaw-yaw)/180*Math.PI)]);
break;
}
}
}
return distances;
}
map.png
Is there anyone who can tell me what's wrong?

Related

How to take notes on PDF files using JavaScript and HTML

I don't understand why this code is not working. No matter how much I fix it, it doesn't work. Is it not available in PDF? If it's not possible, I'd appreciate it if you could tell me how to replace it.
Also, I would like to ask if it is possible to save the handwritten file as a PDF file again, or if it is possible to save it using a DB on the web server, and if possible, please provide an example code.
index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>lol</title>
</head>
<body>
<div class="palette">
<label>색상<input id="color" type="color"></label>
<label>두께<input id="width" type="number" min="1" max="30"></label>
<input type="button" class="btn" id="delete_canvas" value="그림 초기화" onClick="delete_canvas()">
</div>
<iframe width="100%" height="1295" src="./src/krlang.pdf"></iframe>
<canvas id="canvas" width="1600" height="900"></canvas><br>
<script type="text/javascript">
var elements = document.getElementsByClassName("drag-and-drop");
var array = [];
for (var i = 0; i < elements.length; i++) {
array[i] = {}
array[i].top = elements[i].style.top;
array[i].left = elements[i].style.left;
}
function all_reset() {
ret = confirm('모두 재설정합니다.');
if (ret == true) {
for (var i = 0; i < elements.length; i++) {
elements[i].style.top = array[i].top;
elements[i].style.left = array[i].left;
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
}
</script>
<script type="text/javascript" src="canvas.js"></script>
</body>
</html>
canvas.js
var drawing = false;
var before_x = 0;
var before_y = 0;
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.addEventListener('mousemove', draw_canvas);
canvas.addEventListener('mousedown', function(e) {
drawing = true;
var rect = e.target.getBoundingClientRect();
before_x = e.clientX - rect.left;
before_y = e.clientY - rect.top;
});
canvas.addEventListener('mouseup', function() {
drawing = false;
});
function draw_canvas(e) {
if (!drawing){
return
};
var rect = e.target.getBoundingClientRect();
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
var w = document.getElementById('width').value;
var color = document.getElementById('color').value;
var r = parseInt(color.substring(1,3), 16);
var g = parseInt(color.substring(3,5), 16);
var b = parseInt(color.substring(5,7), 16);
ctx.lineCap = 'round';
ctx.strokeStyle = 'rgb('+ r + ',' + g + ',' + b + ')';
ctx.lineWidth = w;
ctx.beginPath();
ctx.moveTo(before_x, before_y);
ctx.lineTo(x, y);
ctx.stroke();
ctx.closePath();
before_x = x;
before_y = y;
}
function delete_canvas(){
ret = confirm('그리기 내용 삭제');
if (ret == true){
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
}
var pen = document.getElementById('pencil');
var era = document.getElementById('eraser');
Edit
I decided to do a webview app instead of running this html code on a web server, please tell me how to do it with a local database

How to pause the animation

I make this image move around the canvas but none of the methods stop it from moving.I make the setInterval to make the move and clear the Interval later by clearInterval in order to stop the motion but seems it won't work
<html>
<head>
<script type="application/javascript">
var ctx = null;
var x_icon = 0;
var y_icon = 0;
var stepX = 1;
var stepY = 1;
var size_x = 221;
var size_y = 184;
var canvas_size_x = 800;
var canvas_size_y = 600;
var anim_img = null;
function draw() {
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
anim_img = new Image(size_x, size_y);
anim_img.onload = function() {
var myvar = setInterval(myAnimation, 10);
function stopMove() {
clearInterval(myVar);
}
}
anim_img.src = 'image/download.jpg';
}
function myAnimation() {
ctx.clearRect(0, 0, canvas_size_x, canvas_size_y);
if (x_icon < 0 || x_icon > canvas_size_x - size_x) {stepX = -stepX; }
if (y_icon < 0 || y_icon > canvas_size_y - size_y) {stepY = -stepY; }
x_icon += stepX;
y_icon += stepY;
ctx.drawImage(anim_img, x_icon, y_icon);
}
</script>
</head>
<body onload="draw();">
<canvas id="canvas" width="800" height="600" style="border:solid 1px;"></canvas>
<button onmousedown="stopMove()">STOP</button>
</body>
</html>
I expected to stop the motion of the download.jpg on click of the STOP button but it won't work
As #Snel23 said, you need to lift stopMove() and myvar out from the draw() context.
var ctx = null;
var x_icon = 0;
var y_icon = 0;
var stepX = 1;
var stepY = 1;
var size_x = 221;
var size_y = 184;
var canvas_size_x = 800;
var canvas_size_y = 600;
var anim_img = null;
var myvar = null; // moving interval handle outside draw()
function draw() {
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
anim_img = new Image(size_x, size_y);
anim_img.onload = function()
{
myvar = setInterval(myAnimation, 10);
}
anim_img.src = 'image/download.jpg';
}
function stopMove() {
clearInterval(myVar);
}
function myAnimation() {
ctx.clearRect(0, 0, canvas_size_x, canvas_size_y);
if (x_icon < 0 || x_icon > canvas_size_x - size_x) {stepX = -stepX; }
if (y_icon < 0 || y_icon > canvas_size_y - size_y) {stepY = -stepY; }
x_icon += stepX;
y_icon += stepY;
ctx.drawImage(anim_img, x_icon, y_icon);
}
If you declare your interval (which you call myVar) at the top level of your code (outside of your functions) and also move your nested function out to the top level, you can access both of them as needed, something like:
// Defines global identifiers
let
ctx = null,
x_icon = 0,
y_icon = 0,
stepX = 1,
stepY = 1,
size_x = 260,
size_y = 175,
canvas_size_x = 400,
canvas_size_y = 180,
anim_img = null,
interval = null; // `interval` is a global variable
const
canvas = document.getElementById("canvas"),
button = document.getElementById("button");
// Calls `stop` when the user clicks the button
button.addEventListener("click", stop);
// Calls `draw` immediately to render the initial canvas
draw();
function draw() {
ctx = canvas.getContext("2d");
anim_img = new Image(size_x, size_y);
anim_img.onload = function() {
// Calls `animate` repeatedly until `interval` is cleared
interval = setInterval(animate, 30);
}
anim_img.src = 'https://www.logomaker.com/wp-content/uploads/2018/12/education1.png';
}
function stop() {
clearInterval(interval);
}
function animate() {
// Re-draws the image at different positions on the canvas
ctx.clearRect(0, 0, canvas_size_x, canvas_size_y);
if (x_icon < 0 || x_icon > canvas_size_x - size_x) { stepX *= -1; }
if (y_icon < 0 || y_icon > canvas_size_y - size_y) { stepY *= -1; }
x_icon += stepX;
y_icon += stepY;
ctx.drawImage(anim_img, x_icon, y_icon);
}
<canvas id="canvas" width="400" height="180" style="border:solid 1px;"></canvas>
<button id="button">STOP</button>

Javascript not displaying in canvas

I've been creating a Flappy Bird game with JavaScript and for some reason, it's stopped displaying in the browser. I've checked the canvas displays by changing the background colour, but the actual JavaScript doesn't. I'm new to JavaScript, so I'm not sure where I'm going wrong. Thank you in advance.
Here is the html file:
<!DOCTYPE html>
<html>
<head>
<title>Flappy Bird using JS</title>
</head>
<body>
<canvas id="canvas" width="288" height="512"></canvas>
<script src="flappyBird.js"></script>
</body>
</html>
And here is the JS:
var cvs = document.getElementById("canvas");
var ctx = cvs.getContext("2d");
// load images
var bird = new Image();
var bg = new Image();
var fg = new Image();
var pipeNorth = new Image();
var pipeSouth = new Image();
bird.src = "images/bird.png";
bg.src = "images/bg.png";
fg.src = "images/fg.png";
pipeNorth.src = "images/pipeNorth.png";
pipeSouth.src = "images/pipeSouth.png";
// some variables
var gap = 85;
var constant = pipeNorth.height+gap;
var bX = 10;
var bY = 150;
var gravity = 1.5;
// on key down
document.addEventListener("keydown",moveUp);
function moveUp(){
bY -= 25;
}
// pipe coordinates
var pipe = [];
pipe[0] = {
x : cvs.width;
y : 0;
}
// draw images
function draw(){
ctx.drawImage(bg,0,0);
for(var i = 0; i < pipe.length; i++){
ctx.drawImage(pipeNorth,pipe[i].x,pipe[i].y);
ctx.drawImage(pipeSouth,pipe[i].x,pipe[i].y+constant);
pipe[i].x--;
if(pipe[i].x == 125){
pipe.push({
x : cvs.width,
y : Math.floor(Math.random()*pipeNorth.height) - pipeNorth.height
});
}
// detect collision
if(bX + bird.width >= pipe[i].x && bX <= pipe[i].x + pipeNorth.width &&
(bY <= pipe[i].y + pipeNorth.height || bY+bird.height >= pipe[i].y+constant)
|| bY + bird.height >= cvs.height - fg.height){
location.reload();
}
if(pipe[i].x == 5){
score++;
}
}
ctx.drawImage(fg,0,cvs.height - fg.height);
ctx.drawImage(bird,bX,bY);
bY += gravity;
ctx.fillStyle = "#000";
ctx.font = "20px Verdana";
ctx.fillText("Score: "+score,10,cvs.height-20);
requestAnimationFrame(draw);
}
draw();

HTML - Canvas element get Base64 data at same scale of canvas

I found that to get the base64 data from a HTML canvas, you had to do canvas.toDataURL();. The problem with this, is that when it gives you the base64, it is scaled to the generic 300 x 150 canvas size, but the actual canvas is 600 x 100. Is there a way to strech the image to be 600 x 100, or to export it in the base64 as such? Thanks in advance!
I had the width and height defined in CSS not HTML, so the document wasn't registering the widths and heights.
Here is the updated code below:
<body>
<script>
var granmoe = 0;
var hai = 5;
var runnin = 0;
while(runnin != hai){
var can = document.createElement("canvas");
can.id = "canvasite"
can.style = "width: 150px; height: 100px; display:none;"
document.body.appendChild(can);
c = document.getElementById('canvasite'),
ctx = c.getContext('2d');
var x = 0
if(runnin == 0){
var endheight = c.height/2
}
var y = endheight;
var widd = 0
while(widd != c.width){
ctx.fillStyle = "rgba("+0+","+255+","+0+","+(255/255)+")";
ctx.fillRect( x, y, 1, 1 );
var ychan = Math.floor((Math.random() * 6) + 1);
if(ychan == 1){
var y=y+2
}else if(ychan == 2){
var y=y+1
}else if(ychan == 3){
var y=y-1
}else if(ychan == 4){
var y=y-2
}else{
var y=y
}
var hig = y
while(hig != c.height){
ctx.fillStyle = "rgba("+0+","+255+","+0+","+(255/255)+")";
ctx.fillRect( x, hig, 1, 1 );
var hig = hig+1
}
var widd = widd+1
var x=x+1
}
{
var endheight = y
var runnin = runnin+1
document.getElementById('canvasite').setAttribute('id','nAn')
var imgm = document.createElement("img");
imgm.src = c.toDataURL();
imgm.id = "imageitem"
imgm.style = "display:none;"
document.body.appendChild(imgm)
var xid = granmoe*(300*(1/hai));
if(granmoe == 0){
var cansfoo = document.createElement("canvas")
cansfoo.id = "fullimage";
cansfoo.style = 'width: '+(hai*150)+'px; height: 100px; display:none;'
document.body.appendChild(cansfoo);
}
var ci=document.getElementById("fullimage");
var ctxi=ci.getContext("2d");
var imd=document.getElementById("imageitem");
ctxi.drawImage(imd,xid,0,(300*(1/hai)),180);
//end
var granmoe=granmoe+1
document.getElementById("imageitem").setAttribute('id','non');
}
}
var base64 = ci.toDataURL();
var bass = document.createElement("img");
bass.src = base64
bass.id = "resiz"
bass.style = "display:none;"
document.body.appendChild(bass);
{
var resize = document.createElement("canvas")
resize.id = "resize";
resize.width = (hai*150);
resize.height = 100;
resize.style = 'display:none;'
document.body.appendChild(resize);
var re=document.getElementById("resize");
var res=re.getContext("2d");
var imag=document.getElementById("resiz");
res.drawImage(imag,0,50,(hai*150),50);
document.write(resize.toDataURL());
}
</script>
</body>

HTML5 drawImage - Not working in Chrome while dragging

Im trying to drag and drop an image in canvas. But when dragging in chrome the image disapears but in Mozilla it works fine. Any help on this would be really appreciated.
HTML File
<head>
<script>
var canvasImages = [];
function imageProp() {
this.imgName = ' ';
this.imgX = 0;
this.imgY = 0;
this.ImgWidth = 1;
this.ImgHeight = 1;
}
function GetFilename(url) {
if (url) {
var m = url.toString().match(/.*\/(.+?)\./);
if (m && m.length > 1) {
return m[1];
}
}
return "";
}
function load(source) {
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext('2d');
var imageObj = new Image();
//Loading image to Canvas
imageObj.onload = function () {
ctx.drawImage(imageObj, 0, 0);
};
imageObj.src = source;
//Inserting properties of image loaded in canvas to an array
var Property = new imageProp;
//Property.imgName = GetFilename(source);
Property.imgName = source;
Property.imgX = 0;
Property.imgY = 0;
Property.ImgWidth = imageObj.width;
Property.ImgHeight = imageObj.height;
canvasImages.push(Property);
}
</script>
</head>
<body>
<img id = "imgID" onclick=" load(this.src)" src = 'download.png'/>
<canvas id="mycanvas" width="1000" height="1000">HTML5 Not Supported</canvas>
<script src="Canvas_js.js"></script>
</body>
Javascript file
(function () {
"use strict";
/*global document*/
/*global clear*/
/*global canvasImages*/
/*jslint devel: true */
/*jslint browser: true */
var canvas, ctx, ghostcanvas, gctx, RedrawInterval = 20, canvasValid = false, clickLoc = {}, isDragging = false, index = 0, selectedIndex = 0;
clickLoc.x = 0;
clickLoc.y = 0;
function drawCanv() {
var i = 0, imageObj;
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (i = 0; i < canvasImages.length; i += 1) {
imageObj = new Image();
imageObj = document.createElement('img');
imageObj.src = canvasImages[i].imgName;
imageObj.onload = function () {
ctx.drawImage(imageObj, canvasImages[i].imgX, canvasImages[i].imgY);
};
}
}
function resizeHandler(index) {
ctx.beginPath();
ctx.strokeRect(canvasImages[index].imgX, canvasImages[index].imgY, canvasImages[index].ImgWidth + 5, canvasImages[index].ImgHeight + 5);
}
function canvasOnClick(e) {
var rect, i = 0;
isDragging = true;
//Get X and Y coordinates of the click
rect = canvas.getBoundingClientRect();
clickLoc.x = e.clientX - rect.left;
clickLoc.y = e.clientY - rect.top;
//Check whether any image is clicked
for (i = 0; i < canvasImages.length; i += 1) {
if (clickLoc.x >= canvasImages[i].imgX && clickLoc.x <= canvasImages[i].imgX + canvasImages[i].ImgWidth && clickLoc.y >= canvasImages[i].imgY && clickLoc.y <= canvasImages[i].imgY + canvasImages[i].ImgHeight) {
selectedIndex = i;
resizeHandler(i);
}
}
}
function canvasMouseUp(e) {
isDragging = false;
}
function canvasMouseMove(e) {
if (isDragging === true) {
canvasImages[selectedIndex].imgX += 5;
drawCanv();
}
}
function init() {
// Defining Canvas and fake canvas
canvas = document.getElementById('mycanvas');
ctx = canvas.getContext('2d');
ghostcanvas = document.createElement('canvas');
ghostcanvas.height = canvas.height;
ghostcanvas.width = canvas.width;
gctx = ghostcanvas.getContext('2d');
// Redrawing canvas for the interval
//setInterval(draw, RedrawInterval);
// Adding Eventlisteners
canvas.addEventListener("mousedown", canvasOnClick, false);
canvas.addEventListener("mouseup", canvasMouseUp, false);
canvas.addEventListener("mousemove", canvasMouseMove, false);
}
init();
}());
Start messing around with
user-select: none;
-webkit-user-select: none;
in your css.

Categories

Resources