logo
down
shadow

Fake CRT effect on Canvas


Fake CRT effect on Canvas

By : Josh Vogelgesang
Date : November 22 2020, 09:00 AM
will help you A quick search gave me this website: WebGL Fake CRT Effect for HTML5 Games, it uses the glfx.js library.
code :
// Make sure you've included the glfx.js script in your code!

// Here I load a PNG with scanlines that I overwrite onto the 2D game's canvas.
// This file happens to be customized for the demo game, so to make this a
// general solution we'll need a generic scanline image or we'll generate them
// procedurally.
// Start loading the image right away, not after the onload event.
var lines = new Image();
lines.src = 'http://i.imgur.com/TAJ0Zkw.png';

window.addEventListener('load', fakeCRT, false);

function fakeCRT() {
    var glcanvas, source, srcctx, texture, w, h, hw, hh, w75;

    // Try to create a WebGL canvas (will fail if WebGL isn't supported)
    try {
       glcanvas = fx.canvas();
    } catch (e) {return;}

    // Assumes the first canvas tag in the document is the 2D game, but
    // obviously we could supply a specific canvas element here.
    source = document.getElementsByTagName('canvas')[0];
    srcctx = source.getContext('2d');

    // This tells glfx what to use as a source image
    texture = glcanvas.texture(source);

    // Just setting up some details to tweak the bulgePinch effect
    w = source.width;
    h = source.height;
    hw = w / 2;
    hh = h / 2;
    w75 = w * 0.75;

    // Hide the source 2D canvas and put the WebGL Canvas in its place
    source.parentNode.insertBefore(glcanvas, source);
    source.style.display = 'none';
    glcanvas.className = source.className;
    glcanvas.id = source.id;
    source.id = 'old_' + source.id;

    // It is pretty silly to setup a separate animation timer loop here, but
    // this lets us avoid monkeying with the source game's code.
    // It would make way more sense to do the following directly in the source
    // game's draw function in terms of performance.
    setInterval(function () {
        // Give the source scanlines
        srcctx.drawImage(lines, 0, 0, w, h);

        // Load the latest source frame
        texture.loadContentsOf(source);

        // Apply WebGL magic
        glcanvas.draw(texture)
            .bulgePinch(hw, hh, w75, 0.12)
            .vignette(0.25, 0.74)
            .update();
    }, Math.floor(1000 / 40));
}


Share : facebook icon twitter icon
How to create a fake throw effect?

How to create a fake throw effect?


By : Guayotenango
Date : March 29 2020, 07:55 AM
To fix the issue you can do I'm learning AS3 and I'm trying to build a little interaction where I can throw a square off the stage. It just need to stay on the x-axis, to be thrown either to the left or right. , Try using this as a base class for the object that you want to throw.
code :
package
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;

    public class ThrowableObject extends Sprite
    {
        // properties
        public var yv:Number = 0;
        public var xv:Number = 0;

        private var _grabbed:Boolean = false;
        private var _gy:int = 0;
        private var _gx:int = 0;

        private var ox:int = 0;
        private var oy:int = 0;

        /**
         * Constructor
         */
        public function ThrowableObject()
        {
            addEventListener(Event.ADDED_TO_STAGE, _init);
        }

        /**
         * Called on dispatch of Event.ADDED_TO_STAGE
         * @param e Event.ADDED_TO_STAGE
         */
        private function _init(e:Event):void
        {
            addEventListener(Event.ENTER_FRAME, _handle);
            addEventListener(MouseEvent.MOUSE_DOWN, _handleClick);
            stage.addEventListener(MouseEvent.MOUSE_UP, _handleRelease);
        }

        /**
         * Called on dispatch of Event.ENTER_FRAME
         * @param e Event.ENTER_FRAME
         */
        private function _handle(e:Event):void
        {
            ox = x;
            oy = y;

            if(_grabbed)
            {
                x = parent.mouseX - _gx;
                y = parent.mouseY - _gy;
            }
            else
            {
                x += xv;
                y += yv;
            }
        }

        /**
         * Called on dispatch of MouseEvent.MOUSE_DOWN
         * @param e MouseEvent.MOUSE_DOWN
         */
        private function _handleClick(e:MouseEvent):void
        {
            grabbed = true;
            parent.addChild(this);
        }

        /**
         * Called on dispatch of MouseEvent.MOUSE_UP
         * @param e MouseEvent.MOUSE_UP
         */
        private function _handleRelease(e:MouseEvent):void
        {
            grabbed = false;
        }

        /**
         * Sets grabbed
         * @param val Boolean representing value to set grabbed as
         */
        protected function set grabbed(bool:Boolean):void
        {
            _grabbed = bool;

            if(_grabbed)
            {
                _gx = mouseX;
                _gy = mouseY;
            }
            else
            {
                xv = x - ox;
                yv = y - oy;
            }
        }
    }
}
Java, fake 3D effect

Java, fake 3D effect


By : Василь Тополюк
Date : March 29 2020, 07:55 AM
wish help you to fix your issue The effect you want to achieve is called Skewing
Take a look at the Skew section @ http://www.javaxt.com/javaxt-core/javaxt.io.Image/
code :
   javaxt.io.Image image = new javaxt.io.Image(java.awt.image.BufferedImage bufferedImage);
    int width = image.getWidth();
    int height = image.getHeight();
    image.setCorners(20, 70,              //UL
                     width-70, 0,         //UR
                     width+20, height-50, //LR
                     50, height);         //LL
canvas (about) 5px line -- add bevel effect to make it 3D -- any ideas? (Sample of desired final effect included)

canvas (about) 5px line -- add bevel effect to make it 3D -- any ideas? (Sample of desired final effect included)


By : Kentse Gabatsoswe
Date : March 29 2020, 07:55 AM
help you fix your problem I think the only way to do that kind of drawing is to draw step by step the curve, and apply at each step a texture perpendicular to the local tangent.
But you seem to want another feature : be able to 'twist' the texture depending on the part of the curve. Here there are so mant options to parameterize this i can't guess how you'll store/interpolate the twist of the texture. So below i just had the texture 'turn' with t, the parameter of the bezier curve.
code :
//  ----------------------------------------------
//  Draw bezier curve filled with 
//    with txCv used as perpendicular texture 
//    signature : drawTexturedBezier ( txCv, a, b, c, d, twisted )
//    a,b,c,d are control points, twisted means
//      do we have to twist the curve.
//          Width of the bezier is == to txCv.width/2 
//          when the draw resolution is tx.height (lower = nicer+slower, 3 seems fine )
//  ----------------------------------------------
function drawTexturedBezier() {
    // build onnly once local vars
    var pt = {
        x: 0,
        y: 0
    };
    var tg = {
        x: 0,
        y: 0
    };
    var lastPt = {
        x: 0,
        y: 0
    };
    drawTexturedBezier = function (txCv, a, b, c, d, twisted) {
        var lineHeight = txCv.height;
        var t = 0;
        var incr = 1 / 1000;
        var pointCount = 0;
        pt.x = a.x;
        pt.y = a.y;
        var thisCoordsForT = coordsForT.bind(null, a, b, c, d);
        var thisTgtForT = tangentForT.bind(null, a, b, c, d);
        // scan the bezier curve by increment of lineHeight distance
        //  on the curve.
        do {
            // update last point
            lastPt.x = pt.x;
            lastPt.y = pt.y;
            // seek next point far enough from previous point
            // just compute one point ahead
            //   using average estimate for t of '1 point ahead'
            thisCoordsForT(t + incr, pt);
            var dx = pt.x - lastPt.x;
            dx *= dx;
            var dy = pt.y - lastPt.y;
            dy *= dy;
            // compute distance to previous point
            var dist = Math.sqrt(dx + dy);
            // compute required t increment
            // considering curve is locally linear
            //  0.92 compensates for the error.
            var tIncrement = 0.92 * incr * (lineHeight / dist);
            t += tIncrement;
            // compute point
            thisCoordsForT(t, pt);
            pointCount++;
            // update regular increment with local one 
            incr = 0.2 * incr + 0.8 * tIncrement;
            // compute tangent for current point
            thisTgtForT(t, tg);
            // draw with perpendicular texture
            drawTexturedLine(txCv, pt, tg, t, twisted);
        } while (t < 1);
    };
    return drawTexturedBezier.apply(this, arguments);
}
// draws a rect centered on pt, for a curve having tg as local tangent
//     having size of : txCv.width/2 X txCv.height
//      using the txCv horizontal pattern as pattern.
function drawTexturedLine(txCv, pt, tg, t, twisted) {
    var lineWidth = txCv.width / 2;
    var lineHeight = txCv.height;
    context.save();
    context.beginPath();
    context.lineWidth = 2;
    context.translate(pt.x, pt.y);
    context.rotate(Math.PI + Math.atan2(-tg.x, tg.y));
    var twistFactor = 0;
    if (twisted) {
        twistFactor = (2 * t + animating * Date.now() / 2000) % 1;
    }
    context.drawImage(txCv,
    twistFactor * lineWidth, 0, lineWidth, lineHeight, -0.5 * lineWidth, -0.5 * lineHeight, lineWidth, lineHeight);
    context.restore();
}
HTML5 Canvas steam effect not displaying correctly without a canvas fill

HTML5 Canvas steam effect not displaying correctly without a canvas fill


By : Theresa Cull
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Use ctx.clearRect(0,0,w,h) to get the transparent background you want.
I have also made some changes.
code :
"use strict"; // this is a javascript directive and must be on the first line of the 
              // script (if included but is not a requirement). 
              // It forces a more code run under more stringent rules. The advantages
              // are many, including making the code run faster.

var imageLoadCount = 0;  // counts the number of image loading, counts down as they load
var readyToAnimate = false; // flag to indicate that resources are available
// image indexes in images array to get correct images in the animation.
const PARTICLE_IMAGE_INDEX = 0;
const BACKGROUND_IMAGE_INDEX = 1;
var images = []; // an array of images 
// What follows is a self evoking function, this will isolate the loading stuff from the
// rest of the script as it is only needed once at start so no point keeping references to it all
// the self invoking function is
//  (function(){...code body})()
// the () at the end forces javascript to run what is inside the () before it.
(function (){        
    function imageLoaded(){ // image onload function "this" is a reference to the image
        imageLoadCount -= 1; // count the loaded image
        // if the count is zero all images have loaded
        if(imageLoadCount === 0){
            readyToAnimate = true;
        }
    }
    // a list of image urls that need to be loaded. 
    const imageURLs = [
        "http://wightfield.com/_temp/smoke_600-60.png",
        "http://wightfield.com/_temp/smoke_600-60.png", // repeating the image just as example
    ];
    imageURLs.forEach(function(url){  // for each image url start the load process
        var img = new Image();
        img.src = url;
        img.onload = imageLoaded; // set the image onload function
        imageLoadCount += 1;  // count the number of images loading
        images.push(img); 
    });
})();  // run the function
var canvas = document.createElement('canvas');
var w = canvas.width = 800;
var h = canvas.height = 700;
var c = canvas.getContext('2d');   
document.body.appendChild(canvas);    

var position = {
    x : 450,
    y : 410
};
var mugPosition = {
    x : w / 3,
    y : 500
};


var particles = [];
var random = function (min, max) {
    // YOU had Math.random() * (max - min) * min; I assume you did not want to multiply by min
    return Math.random() * (max - min) + min;
};
var particleCount = 0;
const ALPHA_CUTOFF = 1/255;
const ALPHA_START = 0.4;
const ALPHA_DECAY = 0.9
// calculate the number of particles need to show each step of the alpha decay
const MAX_PARTICLES = Math.ceil(Math.log(ALPHA_CUTOFF / ALPHA_START) / Math.log(ALPHA_DECAY));
console.log(MAX_PARTICLES)

var draw = function () {
    var i;
    if(readyToAnimate){  // wait for the resources to load 
        c.setTransform(1,0,0,1,0,0); // reset transform         
        c.clearRect(0, 0, w, h);
        // If you want to render a background image do it here. If the image is the size of the
        // canvas then there is no need to clear the canvas and you can delete the line above
        /*  As an example
        c.drawImage(images[BACKGROUND_IMAGE_INDEX],0,0,w,h); // draws image filling the canvas
        */
        if (particles[particleCount % MAX_PARTICLES] === undefined) {
            particles[particleCount % MAX_PARTICLES] = new Particle(position.x, position.y);
        } else {
            particles[particleCount % MAX_PARTICLES].reset(position.x, position.y);
        }
        particleCount += 1;

        for (i = 0; i < particles.length; i++) {
            particles[i].update();
        }
    }else{
        // if you wanted you can add loading progress here
    }
    requestAnimationFrame(draw);
};


function Particle(x, y) {
    this.reset(x, y);
}
Particle.prototype = {
    reset : function (x, y) {
        this.x = x;
        this.y = y;
        this.velX = (random(1, 10) - 5) / 10;
        this.velY = -9;
        this.size = random(3, 6) / 10;
        this.alpha = ALPHA_START ;
        this.image = images[PARTICLE_IMAGE_INDEX];
    },
    update : function () {
        if(this.alpha >= ALPHA_CUTOFF ){  // no point in rendering a invisible sprite
            this.y += this.velY;
            this.x += this.velX;
            this.velY *= 0.99;            
            c.globalAlpha = this.alpha;
            c.setTransform(this.size,0,0,this.size,this.x, this.y);
            c.drawImage(this.image, -this.image.width / 2, -this.image.height / 2);
            this.alpha *= ALPHA_DECAY ;
            this.size += 0.015; //
        }
    }
}
// start the animation. Images may not have loaded yet
requestAnimationFrame(draw);
canvas {
  border: 1px dotted black;
}
JS canvas animation, my effect is accelerating and accumulating, but the speed of the effect is in the console same?

JS canvas animation, my effect is accelerating and accumulating, but the speed of the effect is in the console same?


By : user3552681
Date : March 29 2020, 07:55 AM
I wish this helpful for you Here are a few simple ways you can improve performance:
Commenting out shadowBlur gives a noticeable boost. If you need shadows, see this answer which illustrates pre-rendering. Try using fillRect and ctx.rotate() instead of drawing a path. Saving/rotating/restoring the canvas might be prohibitive, so you could use non-rotated rectangles. Consider using a smaller canvas which is quicker to repaint than one that may fill the entire window.
code :
for (let i = expAr.length - 1; i >= 0; i--) {
  if (!inBounds(expAr[i], canvas)) {
    expAr.splice(i, 1);
  }
}
function inBounds(obj, canvas) {
  return obj.x >= 0 && obj.x <= canvas.width &&
         obj.y >= 0 && obj.y <= canvas.height;
}
this.cn = cn;
this.s = s;
this.w = w;
this.en = en;
this.i = 0;
const rnd = n => ~~(Math.random() * n);
const mouse = {pressed: false, x: 0, y: 0};
let fireworks = [];
let shouldSplice = false;
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");

document.body.appendChild(canvas);
document.body.style.margin = 0;
canvas.style.background = "#111";
canvas.width = innerWidth;
canvas.height = innerHeight;
ctx.shadowBlur = 0;

const fireworksAmt = document.querySelector("#fireworks-amt");
document.querySelector("input[type=range]").addEventListener("change", e => {
  ctx.shadowBlur = e.target.value;
  document.querySelector("#shadow-amt").textContent = ctx.shadowBlur;
});
document.querySelector("input[type=checkbox]").addEventListener("change", e => {
  shouldSplice = !shouldSplice;
});

const createFireworks = (x, y) => {
  const color = `hsl(${rnd(360)}, 100%, 60%)`;
  return Array(rnd(20) + 1).fill().map(_ => ({
    x: x,
    y: y,
    vx: Math.random() * 6 - 3,
    vy: Math.random() * 6 - 3,
    size: rnd(4) + 2,
    color: color
  }));
}
  
(function render() {
  if (mouse.pressed) {
    fireworks.push(...createFireworks(mouse.x, mouse.y));
  }

  ctx.clearRect(0, 0, canvas.width, canvas.height);

  for (const e of fireworks) {
    e.x += e.vx;
    e.y += e.vy;
    e.vy += 0.03;
        
    ctx.beginPath();
    ctx.fillStyle = ctx.shadowColor = e.color;
    ctx.arc(e.x, e.y, e.size, 0, Math.PI * 2);
    ctx.fill();
 
    if (shouldSplice) {
      e.size -= 0.03;
      
      if (e.size < 1) {
        e.dead = true;
      }
    }
  }
  
  fireworks = fireworks.filter(e => !e.dead);
  fireworksAmt.textContent = "fireworks: " + fireworks.length;
  requestAnimationFrame(render);
})();

let debounce;
addEventListener("resize", e => {
  clearTimeout(debounce);
  debounce = setTimeout(() => {
    canvas.width = innerWidth;
    canvas.height = innerHeight;    
  }, 100);
});

canvas.addEventListener("mousedown", e => {
  mouse.pressed = true;
});
canvas.addEventListener("mouseup", e => {
  mouse.pressed = false;
});
canvas.addEventListener("mousemove", e => {
  mouse.x = e.offsetX;
  mouse.y = e.offsetY;
});
* {
  font-family: monospace;
  user-select: none;
}
div > span, body > div {padding: 0.5em;}
<div>
  <div id="fireworks-amt">fireworks: 0</div>
  <div>
    <label>splice? </label>
    <input type="checkbox">
  </div>
  <div>
    <label>shadowBlur (<span id="shadow-amt">0</span>): </label>
    <input type="range" value=0>
  </div>
</div>
Related Posts Related Posts :
  • I want to restrict HTML input autocomplete to 3 letter minimum
  • tinyMCE editor not updating on the fly
  • typescript kendo-ui call method from string
  • HttpCompileException was unhandled by user code (when i am adding c# code in script)
  • Send form data as array of objects to controller in asp.net mvc
  • Javascript, multi file modules and Require.Js
  • how to render a complete new template and leave the application template in ember
  • Hover unrelated divs
  • Permute string until it matches some input?
  • How to fire JQuery change event when input value changed programmatically?
  • AJAX: POST data to a different url
  • checkbox column in jquery datatable
  • Document.evaluate for documents without namespaceURI crashes Microsoft Edge
  • Bootstrap Menu with "More" option Responsive issue
  • Standard inputs not being added to Angularjs Form $Scope
  • Express promise throw error
  • onclick and get in jquery
  • How to get the country code from Google Places API
  • Passing parameters url in Select2
  • Is there any frame work for Marklogic to write javascript code?
  • How to implement a boostrap template over bootstrap-sass gem
  • Why fixed div comes out when horizontally scrolled?
  • How to limit scope of a function in javascript/ jquery
  • Overlapping legend d3.js
  • Apply transition to div
  • Javascript game help - counting with dice
  • How to hide a div from angular controller
  • Can Promise load multi urls in order?
  • How enable Hover event for bootstrap menus?
  • D3 scale.invert() isn't returning date for x
  • Parsing object to array using underscore js or lodash
  • ES6 with React and Browserify
  • AngularJS Factory return type undefined
  • javascript follow html input fields
  • how to declare a double array in javascript for this particular UI
  • Jquery : find length of mixed list
  • Returning the array before the function is complete & Angular JS
  • Javascript set value of class & hidden input in nested divs
  • Register custom filters with vue.js
  • Add class to input parent
  • Angular controller not talking to view
  • Trouble creating "if then" Javascript statement to change background color of page
  • Socket.IO - Middleware and scoping: how should I access global IO object from external middleware?
  • add class when input is valid in angularjs
  • Positioning multiple div elements
  • Checkbox clicking works, deselecting checkbox not working Javascript
  • Adding ajax jQuery File upload
  • Creating a dynamic array within a dynamic array in JQuery
  • Multiple File Upload actions for a single File Input PHP/JS
  • Want to move an added element to a different part of the DOM
  • Why can't I get Angularjs to work?
  • Minimizing browser window in Firefox & Chrome adds white space to right of page
  • I need to insert the date and time of employee stamp in and out into mysql database
  • Making css auto slider
  • why can't I defne the function first?
  • Pagination with MongoDB in Node.js (With Sorting)
  • How to repeat each() without page refresh
  • Position div at position of another div
  • Click handler is called multiple times in jQuery animate
  • How to multiply each element in an array with a different number (javascript)
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co